C++ namespace功能总结

案例背景:你写了一些代码,其中有一个函数名为xyz(),同时另一个可用库里也有一个同名的函数xyz(), 编译器没有办法知道你指的是哪个版本的xyz().

 

解决办法:A namespace is designed to overcome this difficulty and is used as additional information to differentiate similar functions, classes, variables etc. With the same name available in different libraries. Using namespace, you can define the context in which are defined. In essence, a namespace defines a scope.

 

1. Defining a Namespace:(定义一个命名空间)

namespace namespace_name{//code declarations}

To call the namespace-enabled version of either function or variable, prepend the namespace name as follows:

namespace_name::code;

 

2. The using directive: 使用using

You can also avoid prepending of namespaces with the using namespace directive, This directive tells the compiler that the subsequent code is making use of names in the specfied namespace. (我们总想偷懒,不希望每次调用函数或者类时,前面都要加上前缀namespace_name::,于是可以使用using指令,如下例所示,那么程序中调用的函数或类,默认来自std命名空间。)

example: using namespace std;

 

3. Discontiguous Namespaces:不连续的命名空间

A namespace can be defiend in several parts and so a namespace is made up of the sum of its separately deifned parts. The separate parts of a namespace can be spread over multiple files.

 

4. Nested Namespaces:内嵌的命名空间

namespaces can be nested where you can define one namespace inside another namespace as follows:

namespace namespace_name1{

   //code declarations

   namespace namespace_name2{

       //code declarations

   }

}

 

posted @ 2016-03-01 23:25  雨落无声2002  阅读(664)  评论(0编辑  收藏  举报