C++ (15) 命名空间
- 命名空间:由一个程序设计者命名的内存区域
- 比如ns1::a,命名空间限定符+限定名字
- 命名空间声明:
- namespace 命名空间名
- {
- 变量,函数,结构体,类,模板,其他命名空间
- }
- 无命名空间:作用范围在本文件
- namespace // 命名空间没有名字
- { ...... }
- 命名空间的使用方法
- using namespace name 使用整个命名空间。
- using name::variable 使用命名空间中的某一个变量(即使这个命名空间没有被完全打开,我们仍然可以通过这种方式来使用这个空间中的某个变量)
- ::variable 使用默认命名空间中的变量,
- namespace TV=Television; // 别名TV与Television等价
- 在默认情况下,可以直接使用命名空间中的所有标示符。
- 例:
-
#include <iostream> using namespace std; namespace ns1 { const double RATE = 3.3; // 常量 double pay = 0; // 变量 double tax(int distance) // 函数 { return distance*RATE; } namespace ns2 // 嵌套命名空间 { int num = 0; double pay = 1; } } int main() { using namespace ns1; cout << ns1::RATE << endl; // 结果3.3 cout << ns1::tax(3) << endl; // 结果9.9 using ns1::pay; cout << pay << endl; // 结果0,等同于ns1::pay cout << ns1::ns2::num << endl; // 结果0 cout << ns1::ns2::pay << endl; // 结果1 return 0; }
- 使用命名空间注意:标志命名空间std:在std中定义和声明的所有标示符在本文件中都可以作为全局使用。但不能再定义和命名空间std的成员同名的标识符。
- 1. 如果仅仅打开第一层命名空间,即使在程序的运行过程中再通过第一层命名空间去访问第二层命名空间也是无法实现的,例如:
-
#include <iostream> using namespace std; namespace first { int b = 0; namespace first { int i = 5; } } int main() { using namespace first; cout << first::first::i << endl; //错误 return 0; }
-
- 2. 命名空间在嵌套的时候可以使用相同的名字,不过在打开命名空间的时候要按照顺序打开,同时作用域也是不相同的。例如:
-
#include <iostream> using namespace std; namespace first { int i = 0; namespace first { int i = 5; } } int main() { using namespace first::first; cout << i << endl; // 结果为5 cout << first::i << endl; // 结果为0 cout << first::first::i << endl; // 结果为5 }
- 通过using namespace first::first打开了名字为first和first的嵌套命名空间(第一个first嵌套第二first),这个时候实际上我们把两个first都打开了,所以实际上我们可以使用两个命名空间了
- 程序开始运行的时候就已经确定直接打开第二层first的命名空间,所以这个时候打印的i是第二层命名空间对应的i.
- frist::i,也就是打印第一层命名空间中的i。
- first::first::i,也就是打印第二层命名空间中的i。
-
- 3. 一个命名空间下可以嵌套多个命名空间,这多个命名空间可以重名(相当于分开定义空间中变量),不过重名的时候空间中的标示符不允许相同,否则程序运行报错。
-
#include <iostream> using namespace std; namespace first { namespace first { int i = 0; } namespace first { int b = 8; // int i = 2; // 前面已经定义,会有冲突 } } int main() { using namespace first::first; cout << first::first::i << endl; return 0; }
-
- 1. 如果仅仅打开第一层命名空间,即使在程序的运行过程中再通过第一层命名空间去访问第二层命名空间也是无法实现的,例如:
参考文章: