【发布时间】:2012-05-15 19:09:16
【问题描述】:
我想写一个小单例类,看起来像:
#include <vector>
class Interpreter {
private:
static Interpreter* interInstance;
Interpreter() {}
public:
static Interpreter* getInstance();
~Interpreter() {}
};
Interpreter* Interpreter::interInstance = 0;
Interpreter* Interpreter::getInstance(){
if (!interInstance)
interInstance = new Interpreter();
return interInstance;
}
但这会产生这个异常:
multiple definition of `Interpreter::getInstance()
可以通过将类和函数包装在一个命名空间中来纠正此错误。 但我真的不明白为什么我需要一个命名空间。 getInstance() 一个声明一个实现,不是吗?
【问题讨论】:
-
如果您包含来自多个翻译单元的这段代码,那么
getInstance()和interInstance有几种实现方式 -
此外,您应该始终将您的标题包装在标题保护中。
-
您是否使用匿名命名空间,即
namespace { /* stuff */ }? -
是的,在整个文件中
标签: c++ static namespaces