本文共 1314 字,大约阅读时间需要 4 分钟。
class Singleton{public: Singleton() { if (_count == 0) { cout << "进行构造函数" << endl; _count++; } else { cout << "构造失败" << endl; } }private: static int _count;};int Singleton::_count=0;void test(){ Singleton t1; Singleton t2;}int main(){ test(); system("pause"); return 0;}
//只适用于单线程,多线程需要加锁class Singleton{public: static Singleton* GetConstuct() { if (instance == NULL) { instance = new Singleton(); return instance; } return NULL; }private: static Singleton* instance; Singleton() { cout << "进行构造函数" << endl; }};Singleton* Singleton::instance = NULL;void test(){ Singleton* t1 = Singleton::GetConstuct(); Singleton* t2= Singleton::GetConstuct();}int main(){ test(); system("pause"); return 0;}
利用静态构造函数,初始化静态变量的时候创建实例class Singleton{public: static Singleton* GetConstuct() { return instance; }private: Singleton() { cout << "进行构造函数" << endl; } static Singleton* instance;};Singleton* Singleton::instance = new Singleton();void test(){ Singleton* t1 = Singleton::GetConstuct(); Singleton* t2 = Singleton::GetConstuct();}int main(){ test(); system("pause"); return 0;}
转载地址:http://kqstd.baihongyu.com/