C++Singleton实现-静态问题

C++ Singleton Implementation - Problems with static

本文关键字:问题 静态 实现 C++Singleton      更新时间:2023-10-16

我用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;
 }