如果在一個函數中聲明并初始化一個變量后,再次調用時,并不會再次初始化
void func(){ static int b = 0; if (b == 0){ cout << "b is zero" << endl; } else{ cout << "b is not a zero " <<endl; } b++;}
連續兩次調用func(); 輸出的是不同的結果
一次b是0,一個b是1;
這個可以用在單例模式中
template<class T>class singleton{public: static T* &Instance() { static T* pInstance = NULL; if (pInstance==NULL) { pInstance = new T(); } return pInstance; }PRivate: singleton(); };class msg{public: void sayHello(){ cout << "hello" << endl; }};#define DEFINE_SINGLETION_TYPE(impl,g) typedef singleton<impl> g;int _tmain(int argc, _TCHAR* argv[]){ //Msg是一個類 DEFINE_SINGLETION_TYPE(msg, Msg); //調用靜態工廠方法 Msg::Instance()->sayHello(); return 0;}
新聞熱點
疑難解答
圖片精選