Namespaces (C++)

https://msdn.microsoft.com/en-us/library/5cb46ksf.aspx

http://www.cplusplus.com/doc/tutorial/namespaces/

A namespace is a declarative region that provides a scope to the identifiers (the names of types, functions, variables, etc) inside it. Namespaces are used to organize code into logical groups and to prevent name collisions that can occur especially when your code base includes multiple libraries. All identifiers at namespace scope are visible to one another without qualification. Identifiers outside the namespace can access the members by using the fully qualified name for each identifier, for example std::vector<std::string> vec;, or else by a using Declaration for a single identifier (using std::string), or a using Directive for all the identifiers in the namespace (using namespace std;).Code in header files should always use the fully qualified namespace name.


The following example shows a namespace declaration and three ways that code outside the namespace can accesses their members.

namespace ContosoData  
{      
    class ObjectManager   
    {  
    public:  
        void DoSomething() {}  
    };  
    void Func(ObjectManager) {}  
}  

Use the fully qualified name:

ContosoData::ObjectManager mgr;  
mgr.DoSomething();  
ContosoData::Func(mgr);  

Use a using declaration to bring one identifier into scope:

using WidgetsUnlimited::ObjectManager;  
ObjectManager mgr;  
mgr.DoSomething();  
  

Use a using directive to bring everything in the namespace into scope:

using namespace WidgetsUnlimited;  
ObjectManager mgr;  
mgr.DoSomething();  
Func(mgr);  
  


System_CAPS_ICON_note.jpg Note

A using directive can be placed at the top of a .cpp file (at file scope), or inside a class or function definition.

In general, avoid putting using directives in header files (*.h) because any file that includes that header will bring everything in the namespace into scope, which can cause name hiding and name collision problems that are very difficult to debug. Always use fully qualified names in a header file. If those names get too long, you can use a namespace alias to shorten them.


You can declare that you are 'using' a namespace for a specific scope (such as a function). I should note (someone please correct me if I'm wrong) that in C++ you can arbitrarily declare a scope almost anywhere you want, simply by using curly braces.

{ 
  using mynamespace;
  /* rest of your code here */
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值