gpt4 book ai didi

c++ - 为什么单例实例必须在下面的代码中初始化

转载 作者:行者123 更新时间:2023-11-30 04:52:38 25 4
gpt4 key购买 nike

<分区>

#include <iostream>

using namespace std;

class Singleton
{
public:
static Singleton *getInstance();

private:
Singleton(){}
static Singleton* instance;
};

Singleton* Singleton::instance = 0;
Singleton* Singleton::getInstance()
{
if(!instance) {
instance = new Singleton();
cout << "getInstance(): First instance\n";
return instance;
}
else {
cout << "getInstance(): previous instance\n";
return instance;
}
}

int main()
{
Singleton *s1 = Singleton::getInstance();
Singleton *s2 = Singleton::getInstance();
return 0;
}

我不明白为什么单例实例变量应该在下一行中用 0 初始化。单例 * 单例::实例 = 0;因为当我忘记初始化实例时,我得到了错误

singleton.cpp:(.text+0xc): undefined reference to `Singleton::instance'
singleton.cpp:(.text+0x2d): undefined reference to `Singleton::instance'
singleton.cpp:(.text+0x43): undefined reference to `Singleton::instance'
singleton.cpp:(.text+0x5b): undefined reference to `Singleton::instance'
collect2: error: ld returned 1 exit status

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com