Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/158.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 它应该在名称空间中吗?_C++_Namespaces - Fatal编程技术网

C++ 它应该在名称空间中吗?

C++ 它应该在名称空间中吗?,c++,namespaces,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

我是否必须将.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
}

谢谢。

如果我正确理解了这个问题,您可以只使用a::my,然后实现如下方法

using a::my;

void my::doSomething() {}
你能做到。但是,你应该吗


这是一种不常见的做法,它可能会导致使用::Type的
激增
用于.cc文件中使用的命名空间“a”中的每种类型。这是否是一件好事,是由你来决定的,但我反对它:)

我认为更适合包围所有在代码>命名空间内的命名空间中的代码{{}} /Cuth.Bug,因为这是语义上你正在做的事情:你在<代码> A< < /Cord>命名空间中定义元素。但如果您只是定义成员,那么这两件事都会起作用

当编译器发现
void my::foo()
时,它将尝试确定
my
是什么,它将使用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 ) {
   //....
}
//头
名称空间a{
类我的{//。。。
};

std::ostream&operator您也可以使用
使用名称空间a;
并实现代码,而不需要在代码中有一个大的名称空间a{}。名称空间声明用于标题。+1。名称空间中的内容位于
名称空间{}
中。类似的事情不需要缩进,因此确实没有问题。