C ++ Singleton实现 - 静态问题

时间:2011-06-26 23:15:05

标签: c++ static linker singleton linker-errors

我用C ++编程已经有一段时间了。我试图实现一个单例类,但我得到一个未解析的外部符号。你们能指出解决这个问题吗?提前谢谢!

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)

3 个答案:

答案 0 :(得分:9)

您已宣布 Singleton::theInstance,但您尚未定义它。在一些.cpp文件中添加其定义:

Singleton* Singleton::theInstance;

(另外,Singleton::getInstance应该返回Singleton&而不是Singleton。)

答案 1 :(得分:4)

您需要在C ++实现文件中提供<{1}} 之外的类定义的定义:

theInstance

答案 2 :(得分:2)

除了所有其他答案之外,您可以取消私有成员并使用静态范围函数变量:

static Singleton getInstance()
{
   static Singleton * theInstance = new Singleton(); // only initialized once!
   return *theInstance;
 }