命名空间及其用途

时间:2014-08-23 18:19:44

标签: c++ oop namespaces

有什么好处:

1)命名空间
2)包括名称空间中的标题
3)反向"使用"命名空间

1 个答案:

答案 0 :(得分:2)

1)命名空间避免在复杂项目中命名冲突。

例如,boost库和标准库都有一个类regex和一个类thread。如果没有命名空间,则无法将两个库一起使用。使用命名空间,您可以指定名称,例如:boost::regexstd::thread

另一个例子是,当你有多个版本的代码共存时。这个article为库提供了一个很好的例子,使用嵌套的命名空间和适当的using状态。

2)源文件的命名空间

声明/定义不必是连续的。您可以在源文件中有几个命名空间块,引用相同的命名空间。所以在标题或正文中使用没有问题。

实施例: 文件 source.h

namespace cth {
    void doSomethingGreat();    // forward declaration
}

文件 source.cpp

#include "Source.h"
int main()  // not in the cth namespace !  
{
    cth::doSomethingGreat();  // use what has been declared in the header
}
namespace cth {
    void doSomethingGreat( ) {     // define the function of the header
        // ... something great here 
    }
}

例如,如果忘记了函数定义的命名空间,则会出现链接错误。

现在,您可以在打开命名空间后包含标头。它是有效的,但请记住,您的编译器将包含该文件并处理它,就好像它的内容将被写入您包含它的位置。这可能会产生令人惊讶的结果。

例如,如果我稍微改变 source.cpp 中的代码,那么它就像这样开始:

namespace cth {
#include "Source.h"
    // ... something other stuff here  

}

那么它会起作用,但标题中的定义将被理解为 嵌套命名空间 。因此,文件将无法编译,因为函数cth::doSomethingGreat()main()之前没有前向声明。但标题会定义cth::cth::doSomethingGreat()

如果您遵循头文件应该公开使用的原则,则应该根据命名空间使其自包含。

3)使用命名空间有助于工作。

在第一个例子中,您可以:

using boost::regex; 
using std::thread;  

如果您稍后改变主意,可以更改源代码中的使用以切换到其他类(如果他们使用相同的API,则需要更多工作!)。

您可以在任何代码块中定义using,并应用到块的结尾。 您可以在同一个块中使用相同名称添加多个,但如果它产生歧义,则它是非法的。

using cth::doSomethingGreat;
doSomethingGreat();   // will use cth::doSomethingGreat
using oth::doSomethingGreat;   // allowed 
doSomethingGreat();  // ERROR if same signature:  compiler doesn't know if he should use the cth:: or oth:: function.  

但你可以使用不同的集团来区分不同:

{
    using cth::doSomethingGreat;
    doSomethingGreat();  // use what has been declared in the header
}
{
    using oth::doSomethingGreat;
    doSomethingGreat();  // use what has been declared in the header
}