用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;
}