当前位置:嗨网首页>书籍在线阅读

09-使用名称空间

  
选择背景色: 黄橙 洋红 淡粉 水蓝 草绿 白色 选择字体: 宋体 黑体 微软雅黑 楷体 选择字体大小: 恢复默认

I.6 使用名称空间

名称空间有助于组织程序中使用的标识符,避免名称冲突。由于标准库是使用新的头文件组织实现的,它将名称放在std名称空间中,因此使用这些头文件需要处理名称空间。

出于简化的目的,本书的示例通常使用编译指令using来使std名称空间中的名称可用:

#include <iostream>
#include <string>
#include <vector>
using namespace std;  // a using-directive

然而,不管需要与否,都导出名称空间中的所有名称,是与名称空间的初衷背道而驰的。

稍微要好些的方法是,在函数中使用using编译指令,这将使名称在该函数中可用。

更好也是推荐的方法是,使用using声明或作用域解析运算符(::),只使程序需要的名称可用。例如,下面的代码使cin、cout和end1可用于文件的剩余部分:

#include <iostream>
using std::cin;      // a using-declaration
using std::cout;
using std::endl;

但使用作用域解析运算符只能使名称在使用该运算符的表达式中可用:

cout << std::fixed << x << endl;  //using the scope resolution operator

这样做可能很麻烦,但可以将通用的using声明放在一个头文件中:

// mynames — a header file
using std::cin;           // a using-declaration
using std::cout;
using std::endl;

还可以将通用的using声明放在一个名称空间中:

// mynames — a header file
#include <iostream>
namespace io
{
    using std::cin;
    using std::cout;
    using std::endl;
}
namespace formats
{
    using std::fixed;
    using std::scientific;
    using std:boolalpha;
}

这样,程序可以包含该文件,并使用所需的名称空间:

#include "mynames"
using namespace io;