#include <iostream>
#include <iomanip>
#include <cstdio>
#include <cstdlib>
using namespace std;
//实现Singleton模式
//设计一个类,我们只能生成该类的一个实例。
class Singleton
{
public:
static Singleton * getInstance()
{
if(instance == NULL)
instance = new Singleton();
return instance;
}
private:
static Singleton *instance;
Singleton()
{
}
};
Singleton * Singleton::instance; //注意!
int main()
{
Singleton *s1 = Singleton::getInstance();
cout << hex << s1 << endl;
Singleton *s2 = Singleton::getInstance();
cout << hex << s2 << endl;
system("pause");
}
注意代码中注释的地方。
对于C++语言,在类中声明的静态变量,需要在外部再一次定义。对于静态变量,类内部的那个叫声明,C++要求所有实体在任何翻译单元内必须有且只有一个定义,所以得在外部定义。类外定义一次这样才会分配内存。链接才不会出错。
如果没有注释前面的那句,代码运行就会报链接错误。
运行结果: