说实话,我想问一些问题,但只会用到一个问题。静态函数与类的静态指针有什么区别
通过我所见,静态函数可以在外部访问,而不需要创建类对象,所以我假设这些函数来自在程序初始化时创建的默认副本。当一个类通常具有单个用法的私有构造函数并且使用已知方法GetInstance
时,指针将指向的静态变量的地址被返回。问题是你可以多次调用GetInstance
,但指针指向的地址总是相同的,为什么会发生这种情况,其次,它和直接静态函数有什么不同?我知道在GetInstance
我可以访问storage
载体,因为创建了一个“COPY”(参考上面的问题),而功能StoreB
有一个this
指针,这也引发了我的问题,为什么静态函数没有this
指针,因为没有创建副本?
class store
{
private:
store(){};
~store(){};
std::vector<int>storage;
public:
static void Store(int a);
void StoreB(int a);
static store* GetInstance()
{
static store obj;
return& obj;
}
};
void store::StoreB(int a)
{
storage.push_back(a);
}
void store::Store(int a)
{
//storage.push_back(a); //can't
}
int _tmain(int argc, _TCHAR* argv[])
{
store::Store(2);
store::GetInstance()->Store(3 );
store *a = store::GetInstance();
store *b = store::GetInstance();
cout << a << endl //points to the same address
<< b << endl; //points to the same address
}
'GetInstance'只用于创建一个对象。一个实现它的类通常是一个单例。 – chris