我想写一个像这样的小单例类:
#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() 声明和一个实现,不是吗?
最佳答案
将成员初始化和方法的定义移到 header 之外,在实现文件中:
解释器.h
class Interpreter {
private:
static Interpreter* interInstance;
Interpreter() {}
public:
static Interpreter* getInstance();
~Interpreter() {}
};
解释器.cpp
#include "Interpreter.h"
Interpreter* Interpreter::interInstance = 0;
Interpreter* Interpreter::getInstance(){
if (!interInstance)
interInstance = new Interpreter();
return interInstance;
}
在类或结构定义中,static
不会像在外部那样为符号提供内部链接,因此您违反了单一定义规则。
如果多个翻译单元包含一个包含非内联方法的 header 或定义相同的符号,您将遇到多重定义。
关于c++ - 静态函数中的命名空间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10607253/