为什么错误LNK2001:在这种情况下未解析的外部符号?

时间:2012-09-25 01:30:43

标签: c++

  

可能重复:
  Defining static members in C++
  Static method with a field

我在网上找到了关于单例实现的以下代码,并决定尝试一下:

#include <iostream>

class Singleton
{
    Singleton(){}
    static Singleton *s_instance;

public:
    static Singleton* getInstance()
    {
        if(!s_instance)
            s_instance = new Singleton();

        return s_instance;
    }
};

int main()
{
    Singleton::getInstance();
    return(0);
}

看起来非常直截了当。但是当我在Visual Studio中构建它时,它会给出一个链接器错误消息:

main.obj : error LNK2001: unresolved external symbol "private: static class Singleton
* Singleton::s_instance" (?s_instance@Singleton@@0PAV1@A)
C:\Users\boll\Documents\Visual Studio 2010\Projects\hello_world\Debug\hello_world.exe :
fatal error LNK1120: 1 unresolved externals'

为什么在这种情况下“s_instance”未得到解决?

1 个答案:

答案 0 :(得分:0)

我认为您之前应该初始化s_instance=NULL。您可以看到以下链接:http://www.codeproject.com/Articles/1921/Singleton-Pattern-its-implementation-with-C