请高手指点啊——设计模式之单例模式(C++代码实现)
设计模式之单例模式
各位,
我用C++写了设计模式中的单例模式,但是链接时有点问题,还请高手多多指教啊,多谢了。
#include <iostream>
using namespace std;
class Singleton
{
private:
static Singleton *instance;
Singleton()
{
}
public:
static Singleton *GetInstance()
{
if (NULL == instance)
{
instance = new Singleton();
}
return instance;
}
};
int main()
{
Singleton *p1 = Singleton::GetInstance();
Singleton *p2 = Singleton::GetInstance();
if (p1 == p2)
{
cout<<"Two objects is the same instance"<<endl;
}
return 1;
}
在VC++6.0下链接时显示错误:
--------------------Configuration: test - Win32 Debug--------------------
Compiling...
test.cpp
Linking...
test.obj : error LNK2001: unresolved external symbol "private: static class Singleton * Singleton::instance" (?instance@Singleton@@0PAV1@A)
test___Win32_Debug/test.exe : fatal error LNK1120: 1 unresolved externals
Error executing link.exe.
test.exe - 2 error(s), 0 warning(s)