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

欢迎关注

微信关注下方公众号,第一时间获取干货硬货;公众号内回复【pdf】免费获取数百本计算机经典书籍

    C++ namespace功能总结

原创文章受到原创版权保护。转载请注明出处:https://www.ccppcoding.com/archives/229420

非原创文章文中已经注明原地址,如有侵权,联系删除

关注公众号【高性能架构探索】,第一时间获取最新文章

转载文章受原作者版权保护。转载请注明原作者出处!

(0)
上一篇 2023年2月13日 下午2:19
下一篇 2023年2月13日 下午2:19

相关推荐