一个简单的单例模式编译不过去
我经常看到别人这么写个简单的单例模式,然后我就编译了一下,编译不过啊!
WINDOWS XP + VS2010
struct A
{
int i;
};
class Singleton
{
public:
static A* GetSingletion()
{
if (m_ptr == NULL)
{
m_ptr = new A;
}
return m_ptr;
}
private:
static A *m_ptr;
};
int _tmain(int argc, _TCHAR* argv[])
{
A *pa = Singleton::GetSingletion();
[color=#FF0000][/color]
return 0;
}
错误:
1>singleton.obj : error LNK2001: 无法解析的外部符号 "private: static struct A * Singleton::m_ptr" (?m_ptr@Singleton@@0PAUA@@A)
1>C:\Documents and Settings\BOY_SO_KU\My Documents\Visual Studio 2010\Projects\singleton\Debug\singleton.exe : fatal error LNK1120: 1 个无法解析的外部命令
难道是我哪里出错了
[解决办法]
class Singleton{public: static A* GetSingletion() { if (m_ptr == NULL) { m_ptr = new A; } return m_ptr; }private: static A *m_ptr;};A* Singleton::m_ptr = NULL;int _tmain(int argc, _TCHAR* argv[]){ A *pa = Singleton::GetSingletion(); return 0;}
[解决办法]
class Singleton{private: Singleton() { a = 0; }public: static Singleton& GetInstance() { static Singleton ins; return ins; } int a;}int _tmain(int argc, _TCHAR* argv[]){ Singleton::GetInstance().a++; return 0;}