它应该在命名空间中吗?

The*_* do 6 c++ namespaces

我是否必须将.cpp中的代码放在来自相应.h的命名空间中,或者仅仅使用声明来编写?

//file .h
namespace a
{
/*interface*/
class my
{
};
}

//file .cpp

using a::my; // Can I just write in this file this declaration and
             // after that start to write implementation, or
             // should I write:

namespace a //everything in a namespace now
{
//Implementation goes here
}
Run Code Online (Sandbox Code Playgroud)

谢谢.

Dav*_*eas 4

我认为将命名空间中的所有代码包围在一个namespace a { ... }块中更合适,因为从语义上讲,这就是您正在做的事情:您正在a命名空间内定义元素。但如果您只定义成员,那么这两件事都会起作用。

当编译器找到 时void my::foo(),它会尝试确定my是什么,并从中找到using a::my、 解析my并了解您正在定义该a::my::foo方法。

另一方面,如果您使用自由函数,这种方法将会失败:

// header
namespace a {
   class my { // ... 
   };
   std::ostream & operator<<( std::ostream& o, my const & m );
}
// cpp
using a::my;
using std;
ostream & operator<<( ostream & o, my const & m ) {
   //....
}
Run Code Online (Sandbox Code Playgroud)

编译器很乐意将上面的代码翻译成程序,但它实际上做的是std::ostream& a::operator<<( std::ostream&, a::my const & )在头文件中声明——而不是实现——并std::ostream& ::operator<<( std::ostream &, a::my const & )在cpp文件中定义,这是一个不同的函数。使用 Koening 查找,每当编译器看到cout << objwith objof 类型时a::my,编译器都会在coutand my( std, and a) 的封闭命名空间中查找,并会发现在 中存在a::operator<<已声明但从未定义的类型namespace a。它将编译但不会链接您的代码。