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

why error LNK2001: unresolved external symbol in this case?

本文关键字:外部 符号 这种情况下 错误 LNK2001 为什么      更新时间:2023-10-16

可能的重复项:
在C++
中定义静态成员 具有字段的静态方法

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

#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:UsersbollDocumentsVisual Studio 2010Projectshello_worldDebughello_world.exe :
fatal error LNK1120: 1 unresolved externals'

为什么在这种情况下"s_instance"没有解决?

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