#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;
}
网友评论