起因还是我做错了题,平时只是使用std来完成编码,没有细究过,老师也是一语带过。
等到了真正纠结变量作用域的时候,才发现命名空间里面大有学问。

命名空间这个概念,作为附加信息来区分不同库中相同名称的函数、类、变量等。使用了命名空间即定义了上下文。本质上,命名空间就是定义了一个范围。
using namespace 指令,这样在使用命名空间时就可以不用在前面加上命名空间的名称。
- #include <iostream>
-
- using namespace std;
-
- // 第一个命名空间
- namespace first_space {
- void func() {
- cout << "Inside first_space" << endl;
- }
- }
- // 第二个命名空间
- namespace second_space {
- void func() {
- cout << "Inside second_space" << endl;
- }
- }
-
- int main() {
-
- // 调用第一个命名空间中的函数
- first_space::func();
-
- // 调用第二个命名空间中的函数
- second_space::func();
-
- return 0;
- }
同名变量让人头疼,因为不同的范围内声明的不同类型同名变量会覆盖,而离开指定范围后又会变回去。
命名空间是一种区分的方法:
- #include <iostream>
-
- #define endl "\n"
- using namespace std;
-
- double a;//1号
-
- int main() {
- int a = 10;//2号
- {
- int a = 20;//3号
- double b;
- ::a = 20.5;//1号
- b = ::a + a;//1号 +3号
- cout << "a=" << a << " " << "b=" << b << endl;//输出3号
- cout << "::a=" << ::a << endl;//输出1号
- }
- cout << "a=" << a << endl;//输出2号
- cout << "::a=" << ::a << endl;//输出1号
- return 0;
- }

image-20201114105832181
全局变量 a 表达为 ::a,用于当有同名的局部变量时来区别两者。
感谢现在的好奇,为了能成为更好的自己。