Can namespaces be nested in C++?

 

  

  In C++, namespaces can be nested, and resolution of namespace variables is hierarchical.

  For example, in the following code, namespace inner is created inside namespace outer, which is inside the global namespace. In the line “int z = x”, x refers to outer::x. If x would not have been in outer then this x would have referred to x in global namespace.

 1 #include <iostream>
 2 using namespace std;
 3 
 4 int x = 20;
 5 namespace outer 
 6 {
 7     int x = 10;         
 8     namespace inner 
 9     {
10         int z = x; // this x refers to outer::x
11     }
12 }
13 
14 int main()
15 {
16     std::cout<<outer::inner::z; //prints 10
17     getchar();
18     return 0;
19 }

  Output of the above program is 10.

  On a side node, unlike C++ namespaces, Java packages are not hierarchical.

 

  Also in C++, namespaces are the only entity that allowed to span across multiple files. No other syntactic rules are allowed. For example, we can't split class definition across files nor structure definition.

 

 

 

  Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.


  转载请注明:http://www.cnblogs.com/iloveyouforever/

  2013-11-27  14:44:04

转载于:https://www.cnblogs.com/iloveyouforever/p/3445666.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值