【问题标题】:namespace in static functions静态函数中的命名空间
【发布时间】: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


【解决方案1】:

将定义移到标头之外,在实现文件中,用于成员初始化和方法:

Interpreter.h

class Interpreter {

private:
    static Interpreter* interInstance;
    Interpreter() {}

public:
    static Interpreter* getInstance();
    ~Interpreter() {}

};

Interpreter.cpp

#include "Interpreter.h"
Interpreter* Interpreter::interInstance = 0;

Interpreter* Interpreter::getInstance(){
if (!interInstance)
    interInstance = new Interpreter();

return interInstance;
}

在类或结构定义内部,static 不像外部那样提供符号内部链接,因此您违反了单一定义规则

如果多个翻译单元包含一个包含非内联方法或定义相同符号的标头,则会遇到多个定义。

【讨论】:

  • 可能值得添加一个指针,指向 C++ 中“静态”的许多不一致含义的一些更大的描述,但我认为单行解释与任何人在一个中所做的一样好句子。
猜你喜欢
  • 1970-01-01
  • 2010-09-14
  • 2010-12-22
  • 1970-01-01
  • 2010-11-28
相关资源
最近更新 更多