0

可能重复:使用字段
定义 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:\Users\boll\Documents\Visual Studio 2010\Projects\hello_world\Debug\hello_world.exe :
fatal error LNK1120: 1 unresolved externals'

为什么s_instance在这种情况下 ' ' 未解决?

4

1 回答 1

0

I think you should initialize s_instance=NULL before. You can see the following link: http://www.codeproject.com/Articles/1921/Singleton-Pattern-its-implementation-with-C

于 2012-09-25T01:54:13.077 回答