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

   }

}

 

转载于:https://www.cnblogs.com/cbyzju/p/5233313.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值