class Singleobject
{
private:
static Singleobject* instance;
Singleobject() {
instance = 0;
}
public:
static Singleobject* get_instance()
{
if (!instance)
instance = new Singleobject;
return instance;
}
void showMessage()
{
cout << "Inside Singleobject::showMessage()\n";
}
};
//Singleobject *Singleobject::instance = 0;
int main()
{
Singleobject *obj = Singleobject::get_instance();
(*obj).showMessage();
}
在注释Singleobject *Singleobject::instance = 0;
并编译代码时,给出上面的代码,它将返回错误,如下所示:
/tmp/ccWE4wn4.o: In function `Singleobject::Singleobject()':singletondemo.cpp:(.text._ZN12SingleobjectC2Ev[_ZN12SingleobjectC5Ev]+0xb): undefined reference to `Singleobject::instance'
/tmp/ccWE4wn4.o: In function `Singleobject::get_instance()':
singletondemo.cpp:(.text._ZN12Singleobject12get_instanceEv[_ZN12Singleobject12get_instanceEv]+0xc): undefined reference to `Singleobject::instance'
singletondemo.cpp:(.text._ZN12Singleobject12get_instanceEv[_ZN12Singleobject12get_instanceEv]+0x2d): undefined reference to `Singleobject::instance'
singletondemo.cpp(.text._ZN12Singleobject12get_instanceEv[_ZN12Singleobject12get_instanceEv]+0x34): undefined reference to `Singleobject::instance'
collect2: error: ld returned 1 exit status
但是当我删除该注释时,代码将成功编译。我相信我已经在私有构造函数本身中有效地完成了Singleobject *Singleobject::instance = 0;
的操作,因此该注释代码是否保留都无关紧要。谁能解释为什么我会得到这种行为?