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