說實話,我想問一些問題,但只會用到一個問題。靜態函數與類的靜態指針有什麼區別
通過我所見,靜態函數可以在外部訪問,而不需要創建類對象,所以我假設這些函數來自在程序初始化時創建的默認副本。當一個類通常具有單個用法的私有構造函數並且使用已知方法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