C ++在源文件中使用命名空间

时间:2010-11-08 09:32:24

标签: c++ namespaces

假设我正在创建一个项目,并且我将项目中的大多数项目都放在名为Project的名称空间中。我在名为MainProject的名称空间Project中定义了一个类。

在源文件中,要实现该类,我是否'使用命名空间Project;'或者我将它包装在'名称空间Project {...}'巢中?

4 个答案:

答案 0 :(得分:7)

给定标题“n.h”:

namespace n{
  extern void f();
}

以下 未在命名空间f()中定义n(从此处开始,我将其称为n::f

#include "n.h"
using namespace n;

void f(){ }

如果您尝试在任何地方引用n::f,则会收到链接时错误。以上定义了全局命名空间中的f。这确实定义了n::f

#include "n.h"
void n::f(){ }

这也是:

#include "n.h"
namespace n{
  void f(){ }
}

但有一个缺点,如果你错误输入名称或签名,你将向命名空间添加一个新函数并保持void n::f()未定义,导致半恼人的链接时错误。

当涉及课程时,情况会有所不同:

namespace n{
  class c{
    void f();
  };
  extern c operator + (const c&, const c&); // I'll use Matthieu M.'s example
}

这没关系,因为没有全局c

#include "n.h"
using namespace n;
void c::f(){ }

但是,如果您尝试添加两个c,则以下情况会导致链接时错误,原因与首次尝试定义n::f()的原因相同:

#include "n.h"
using namespace n;
c operator + (const c &a, const c &b){ /* blah blah */ } // define global +

此方案还会导致链接时错误(或者甚至是编译错误,具体取决于::c::f的定义位置):

class c{ // a global c, defined in some header somewhere
  void f();
};

#include "n.h"
using namespace n;
void c::f(){ } // define the global c::f (a possible redefinition) and n::c::f remains undefined!

答案 1 :(得分:3)

两种方法都很好,这实际上是一种品味(或命名冲突)。我通常不做,只是在必要时添加名称空间。

答案 2 :(得分:2)

最好重新打开相同的命名空间,然后提供类的实现,而不是在不同的(封闭的)命名空间中。这主要来自模块化及其相关的利益前景。

答案 3 :(得分:1)

using namespace xxx;语法存在(细微)问题。其中名称冲突......

一般来说,最好不要使用它。我建议重新打开命名空间,而不是在名称空间名称前添加标识符,但这更属于品味。

微妙问题的例子:

// header
namespace foo
{
  struct Bar
  {
    explicit Bar(int i);
    int x;
  };
  Bar operator+(Bar lhs, Bar rhs);
}

// source
#include "the header here"

using namespace foo;

Bar operator+(Bar lhs, Bar rhs)
{
  return Bar(lhs.x + rhs.x);
}

引发编译错误。