c++入门之再话命名空间的意义

c++中使用了命名空间这一概念,通过下面这个代码,我们将深刻认识到命名空间的重要作用和意义:

 1 # include"iostream"
 2 using namespace std;
 3 
 4 namespace A{
 5     int x{ 1 };
 6     void fun()
 7     {
 8         cout << "A" << endl;
 9     }
10 
11 }
12 
13 namespace B{
14     int x{ 2 };
15     void fun()
16     {
17         cout << "B" << endl;
18     }
19     void fun2()
20     {
21         cout << "2B" << endl;
22     }
23 }
24 using namespace B;
25 int main()
26 {
27     //using namespace A;
28     cout << x << endl;
29     fun();
30     system("pause");
31     return 0;
32 }

上面这个代码是很好的认识命名空间的例子:

名称空间A和B中都定义了变量x和函数fun.如果我们不声明名称空间,那么main()将无法识别x,和fun究竟来自于A,还是来自于B.。而且,命名空间有利于工程的管理,即不同的工程文件使用的变量名称有可能相同,但如果对他们定义了自己的命名空间的话,则能够进行有效的管理.

本质上,使用cin ,cout需要声明std名称空间也来源于此.下面c++ prime中已经描述了这一点:

原文地址:https://www.cnblogs.com/shaonianpi/p/9769692.html