命名空间是一个极其重要的内容啊。命名空间保存着大量的变量名,函数名,类名,宏名,对象名。使用命名空间,防止发生命名冲突。
从using namespace std 开始说起。std中保存着c++标准程序库中的所有标识符。
对于#include ”iostream“和#include <iostream>前者是c中的头文件,对于其中的内容全部是在全局命名空间的,而后者为c++标准为了正确使用命名空间,将其中的命名都存储在std中,所以,要使用iostream中的内容,必须要加上"using namespace std"
命名空间可以是全局的,也可以在另一命名空间中,但不能位于类或者代码中,命名空间中声明的标识符默认具有外部链接特性。c++标识符的作用域分为 全局,命名空间,类,代码块,四级。全局变量等即是存在一个全局的命名空间中。
定义命名空间:
namespace name{
}
namespace{
}
命名空间也可以没有名字。命名空间只能定义,不能声明。
当在命名空间中调用其他命名空间的标识符时,使用 namespace::thing 当一个命名空间在另一个命名空间内时,可以直接调用上一级的标识符,而外侧的命名空间不能直接调用内部明明空间的标识符,因为它在内部命名空间的外部了。
namespace first{
int firstint=0;
namespace second{
int secondint=++firstint;//在first内部,first中命名的变量对其可见
}
//int third=secondint;//出错,不能使用外部命名空间中的变量
int forth=second::secondint;
using namespace second;
int third=secondint;
}
命名空间是开放的,可以随时将新成员加入已有的命名空间中。
namespace second{
int thirdint;
}
using first::second::secondint;
using second::funA;
funA();
secondint=0;
可以看出,当上上断代码尝试进行添加成员进命名空间时,却没有成功,因为此时成了在全局的命名空间中定义一个新的命名空间了。所以,应该是这样进行增加的:
namespace first{
namespace second{
int thirdint;
void funA(){
thirdint=5;
}
}
}