c++ private static 成员变量如何初始化?

来源:互联网 发布:c语言char范围怎么求 编辑:程序博客网 时间:2024/06/16 14:17

用c++实现单例设计模式的时候,初始化private static 成员变量折腾了一会儿,这种细节确实记得不清楚。


#include <iostream>using namespace std;class Singleton{private:static Singleton* st;//static Singleton* st = NULL; //错误Singleton(){}public:static Singleton* getInstance(){if (st == NULL){st = new Singleton();}return st;}void show(){cout << st << endl;}};Singleton* Singleton::st = NULL; //正确,只能在类外初始化,如若不在此初始化会报连接错误int main(){//Singleton* Singleton::st = NULL; //错误Singleton* st = Singleton::getInstance();Singleton* st1 = Singleton::getInstance();if (st == st1){cout << "两个对象是相同的实例。" << endl;}return 0;}



0 0