c++ - 静态函数中的命名空间

标签 c++ static namespaces

我想写一个像这样的小单例类:

#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/

相关文章:

c++ - RVO 和 NRVO 优化 + C++11 move 运算符

C++类成员作为数组,打包失败案例

html - 如何在Django2.0中使用html或css添加背景

c++ - 静态库链接,C++,VS Express 2013

c++ - 在友元声明中使用限定名称的规则是什么?

c++ - 在 ANTLR4 的 Lexer 中切换流

c++ - Catch2 单元测试未与 CMake 项目一起运行

c++ - 现代 C++ 中的全局变量

r - WGCNA 共享统计方法的命名空间

javascript - 从另一个js文件中的javascript函数调用命名空间函数的问题