c++学习笔记(namespace)
# C++为什么要引入命名空间?
假设有两个班级,A班有位同学张三,B班也有位同学叫张三,因为某种原因,两个班级需要合并,班级合并后就有两个名叫张三的同学,老师需要点名同学回答问题时,那到底该谁起立回答呢?这就产生冲突了,通常的办法可能是把年龄大的叫大张三,年龄小的叫小张三,这样就能够解决这个冲突了;而程序也是一样的,对于C/C++来说,我们编译程序后最终得到的都是一个bin文件,里面的符号都是没有隔离的,所以也会存在这种冲突;在C语言中我们基本只能靠程序员自己来规避这个问题,比如:函数名或变量名尽量带有特殊标识前缀或后缀;不会被外部文件访问的文件内全局变量与函数使用static修饰;而在C++中有了更好的解决方案,那就是命名空间。
你可以认为C++的命名空间就是在你编写的函数或变量名在编译的时候编译器又给你添加了一个前缀,用语言的这种特性来解决冲突,而尽量不依靠程序员自身来解决。
# 语法
namespace ns{
/*
...
*/
};
#使用方法
1//使用此种方法,ns1内的成员在本文件此句代码后都是可见的
2using namespace ns1;
3//使用此种方法,仅仅ns1内的print成员在本文件此句代码后是可见的
4using ns1::print;
5//一般我们使用的都是这种方法,哪里用就在哪里指明
6ns1::print();
7//默认命名空间的两种访问方式,有声明的地方都可以使用
8::func();
9func();
# 测试程序(第一种使用方法)
1//test.hpp
2
3#ifndef __TEST_HPP
4#define __TEST_HPP
5
6namespace ns1{
7 int data1;
8 void print(void);
9 namespace ns2 {
10 int data2;
11 void print(void);
12 };
13};
14
15#endif/*__TEST_HPP*/
1//test.cpp
2
3#include "test.hpp"
4
5#include
6
7//编译
8//g++ test.cpp
9
10void func(void)
11{
12 std::cout << "hello" << std::endl;
13}
14
15using namespace ns1;
16using namespace ns1::ns2;
17
18int main(int argc,char *argv[])
19{
20 //默认命名空间
21 func();
22 ::func();
23
24 data1 = 5;
25 ns1::print();
26 data2 = 6;
27 ns1::ns2::print();
28
29 return 0;
30}
31
32void ns1::print(void)
33{
34 std::cout << data1 << std::endl;
35}
36
37void ns1::ns2::print(void)
38{
39 std::cout << data2 << std::endl;
40}
## 运行结果
hello
hello
5
6
## 结论
命名空间可以嵌套;
不同命名空间内允许同名成员存在;
不同命名空间存在同名成员时,使用的时候任然需要指明其所在的命名空间(代码第25及27行);
默认命名空间相当于具有全局属性,只要有声明就能访问;
# 测试程序(第二种使用方法)
1//test.cpp
2
3#include "test.hpp"
4
5#include
6
7//编译
8//g++ test.cpp
9
10using ns1::data1;
11using ns1::print;
12using ns1::ns2::data2;
13using ns1::ns2::print;
14
15int main(int argc,char *argv[])
16{
17 data1 = 5;
18 ns1::print();
19 data2 = 6;
20 ns1::ns2::print();
21
22 return 0;
23}
24
25void ns1::print(void)
26{
27 std::cout << data1 << std::endl;
28}
29
30void ns1::ns2::print(void)
31{
32 std::cout << data2 << std::endl;
33}
## 运行结果
5
6
## 结论
这种方式和第一种方式效果一样,只是这种方式可以有选择性,可控;
# 测试程序(第三种使用方法)
1//test.cpp
2
3#include "test.hpp"
4
5#include
6
7//编译
8//g++ test.cpp
9
10int main(int argc,char *argv[])
11{
12 ns1::data1 = 5;
13 ns1::print();
14 ns1::ns2::data2 = 6;
15 ns1::ns2::print();
16
17 return 0;
18}
19
20void ns1::print(void)
21{
22 std::cout << ns1::data1 << std::endl;
23}
24
25void ns1::ns2::print(void)
26{
27 std::cout << ns1::ns2::data2 << std::endl;
28}
## 运行结果
5
6
## 结论
虽然使用时可能需要写一串的命名空间标识符,但是给人的第一印象很好,一眼就能看出来自哪儿;
# 综合结论
有三种使用方式,但是在方法(函数)实现的地方必须指明其从属于哪个命名空间。
# 匿名命名空间
匿名命名空间即没有给定命名空间的名字,这样对于外部(文件)来说不知道名字也就无法访问了,所以其作用就是限定匿名命名空间中的成员只具有文件内可见性,而不具备文件外可见性(和C语言中文件内全局函数或变量被static修饰一样)。
## 测试程序
1//test.cpp
2
3#include
4
5//编译
6//g++ test.cpp
7
8namespace {
9 int data;
10 void print_word(void)
11 {
12 std::cout << "word" << std::endl;
13 }
14};
15
16int main(int argc,char *argv[])
17{
18 data = 5;
19 print_word();
20
21 return 0;
22}
## 运行结果
word
# 注意
三种方式是并存的,可以只用一种也可以几种混用都是没问题。





