命名空间对应一组标识符的可见区域。通过创建命名空间,我们可以对类、对象和函数等实体进行分组,其意义在于实现同一个标识符在不同命名空间的不同含义。
最常用的命名空间:std“helloworld”程序中的using namespace std;语句是绝大多数c++学习者对于namespace的第一印象。std是一个特殊的命名空间,c++标准库中的所有文件都在std命名空间中声明其所有实体,如iostream中定义的cin, cout等。
命名空间的定义格式:
namespace identifier
{
entities
}
<例1>
namespace myNamespace
{
int a, b;
}
通过上述代码,我们定义了名为myNamespace的命名空间,并定义了int型变量a和b作为该命名空间内的普通变量。
嵌套
<例2>
namespace firstSpace
{
int a;
namespace secondSpace
{
int b;
}
}
命名空间的定义支持嵌套,即标准声明格式中的entities可为namespace;
命名空间外变量访问为了从命名空间之外访问变量,需要使用范围运算符::。例如,要从myNamespace外访问其变量,我们可以编写:
myNamespace::a myNamespace::b
此功能对于解决全局对象或函数redefinition of 即标识符重定义的问题比较有效。
<例3>
#includeusing namespace std; namespace car { int speed; } namespace plane { int speed; } int main() { car::speed = 120; plane::speed = 280; cout << "Speed of car is " << car::speed << " km/h" << endl; cout << "Speed of plane is " << plane::speed << " km/h" << endl; } # Speed of car is 120 km/h # Speed of plane is 280 km/h
以上代码中,我们在名为car与plane的两个命名空间中各自定义了int型变量speed,借助范围运算符分别对其进行赋值,并输出结果。由于两个名为speed的变量处于不同的命名空间中,没有出现重定义的bug。
关键词: using功能一:将命名空间中的名称引入当前声明区域。
<例4>
#includeusing namespace std; namespace car { int speed; int weight; } namespace plane { int speed; int weight; } int main() { using car::speed; using plane::weight; speed = 120; car::weight = 1000; plane::speed = 280; weight = 70000; cout << "Speed of car is " << speed << " km/h" << endl; cout << "Weight of car is " << car::weight << " kg" << endl; cout << "Speed of plane is " << plane::speed << " km/h" << endl; cout << "Weight of plane is " << weight << " kg" << endl; } # Speed of car is 120 km/h # Weight of car is 1000 kg # Speed of plane is 280 km/h # Weight of plane is 70000 kg
以上代码中,通过using引入了car中定义的speed,以及plane中定义的weight,则使用这两个变量时无需再使用范围运算符。而未引入的car::weight与plane::speed仍需以此格式使用。
功能二:引入整个命名空间
如using namespace std;将std空间内的所有实体引入,可以直接使用。
using仅在声明的代码块中有效,若直接在全局范围内使用,则整个代码中有效。
命名空间的别名可根据以下格式为现有命名空间声明备用名称:
namespace new_name = current_name;
一般新声明的名称长度较短,为方便使用。



