相关内容:
命名空间可作为附加信息来区分不同库中相同名称的函数、类、变量等。使用了命名空间即定义了上下文。本质上,命名空间就是定义了一个范围。举一个计算机系统中的例子,一个文件夹(目录)中可以包含多个文件夹,每个文件夹中不能有相同的文件名,但不同文件夹中的文件可以重名。
定义命名空间
命名空间的定义使用关键字 namespace
,后跟命名空间的名称,如下所示:
1 | namespace namespace_name { |
为了调用带有命名空间的函数或变量,需要在前面加上命名空间的名称,如下所示:
1 | name::code; // code 可以是变量或函数 |
可以使用 using namespace
指令,这样在使用命名空间时就可以不用在前面加上命名空间的名称。这个指令会告诉编译器,后续的代码将使用指定的命名空间中的名称。
不连续的命名空间
命名空间可以定义在几个不同的部分中,因此命名空间是由几个单独定义的部分组成的。一个命名空间的各个组成部分可以分散在多个文件中。所以,如果命名空间中的某个组成部分需要请求定义在另一个文件中的名称,则仍然需要声明该名称。
嵌套的命名空间
命名空间可以嵌套,您可以在一个命名空间中定义另一个命名空间,如下所示:
1 | namespace namespace_name1 { |
您可以通过使用 :: 运算符来访问嵌套的命名空间中的成员:
1 | // 访问 namespace_name2 中的成员 |
代码相关内容:
bs.h:
1 |
|
bs.cpp
:
1 |
|
main.cpp
:
1 |
|