【发布时间】:2012-09-25 01:30:42
【问题描述】:
可能重复:
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'没有得到解决?
【问题讨论】:
-
你需要在类外定义
s_instance。 -
知道了。谢谢克里斯和神秘主义者。
-
这里其实有个小问题:静态数据成员需要在类外定义一次,这是c++规则。但为什么?静态成员函数 'getInstance()' 如果我们使用作用域 ::,则具有可见性,但为什么 's_instance' 会导致未解析的外部符号错误?
标签: c++