C++Singleton实现-静态问题
C++ Singleton Implementation - Problems with static
我用C++编程已经有一段时间了。我试图实现一个singleton类,但我得到了一个未解析的外部符号。你们能指出解决这个问题的方法吗?提前感谢!
class Singleton
{
Singleton(){}
Singleton(const Singleton & o){}
static Singleton * theInstance;
public:
static Singleton getInstance()
{
if(!theInstance)
Singleton::theInstance = new Singleton();
return * theInstance;
}
};
错误:
错误3错误LNK1120:1个未解析的外部
错误2错误LNK2001:未解析的外部符号
"private: static class Singleton * Singleton::theInstance" (?theInstance@Singleton@@0PAV1@A)
您已经声明了Singleton::theInstance
,但尚未定义。请在一些.cpp文件中添加其定义:
Singleton* Singleton::theInstance;
(此外,Singleton::getInstance
应该返回Singleton&
而不是Singleton
。)
您需要在类声明之外的C++实现文件中提供theInstance
的定义:
Singleton *Singleton::theInstance;
除了所有其他答案之外,您还可以去掉私有成员并使用静态作用域函数变量:
static Singleton getInstance()
{
static Singleton * theInstance = new Singleton(); // only initialized once!
return *theInstance;
}
相关文章:
- 静态数据成员的问题-修复链接错误会导致编译器错误
- 基于boost的程序的静态链接——zlib问题
- 使用静态成员声明类时遇到问题
- 使用转换器提升 Python 问题 - 静态链接
- 关于读取有效 c++ 第 4 项(将非局部静态变量替换为局部静态变量)的问题
- (2 问题)"类"类型重新定义(即使 #pragma 一次),以及静态函数内的静态成员对象初始化?
- public:静态常量字符串声明/初始化问题
- 初始化与类类型相同的静态成员(静态初始化顺序问题)
- 将非静态函数绑定到回调时出现问题
- 在 C++ 中使用静态映射的奇怪问题
- 在 x86 32 位上的静态类实例中解决此问题
- 共享库中 __attribute__((构造函数)) 的全局/静态变量初始化问题
- MSYS2静态QT未定义的参考问题
- 这是静态库依赖树中的菱形问题吗?
- 静态 QT 编译问题
- 使用许多静态成员有问题
- 静态联系Intel TBB的问题
- VS 2017 C 静态LIB与 /MD项目依赖性问题编辑
- 创建静态数据成员的代码有什么问题
- dll导出/init问题(静态vars-init?)Visual Studio C++