namespace 的用法

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。

 做下namespace 学习的笔记.如果有人想彻底了解namespace 可看<thinking in C++>中414页.

1.You can subdivide the global name space into more managable pieces using the namespace feature of C++.(说明了namespace 的功能).

The namespace keyword similar to class ,struct ,enum and union,puts the names of its members in a distinct space.While the other keyword  have additonal purposes. The creation of a new namespace is the only purpose for namespace.


namespace  Mylib




2. C++ deprecates the use of file statics in favor of the unnamed namespace.




int main()

} can refer to a name within a namespace in three ways by specifying the name unsing the scope resolution operator (::),

with a using directive to introduce all names in the namespace (using namespace ***;), or with a using declaration to introduce names one  at a time (using **::**);



The key thing to rember is that when you introduce a global  using directive (via a " using namespace "outside of any scope)  ,you have thrown open the namespace for that file,this is usually fine for an implementation file(a "cpp" file) .because the using directive is only in effect until the end of the compilation of that file.That is , it doesn't  affect any other files  so  you can adjust the control of the namespaces one implementation at a time.

Header files are a different issue.In header files you should either use explicit qualification or scoped using directives and using declarations.


总结: 在头文件定义命名空间.在头文件命名空间中,用::  或者 using **::**;

         不用using namespace ***;防止嵌套引起的冲突.

        在实现文件中 ,用using namespace ***;如果发生了命名冲突,在改用

        using **::**;