Namespace:命名空間

來源:互聯網
上載者:User

Namespace:命名空間。

命名空間是用來解決不同的類和函數擁有相同的名稱的問題。解決了命名衝突的問題。

namespace gxg

{

   class A;

   void BFunction();

}

 

namespace gaoxiaoguang

{

   class A;

   void BFunction();

}

 

使用方法:

gxg::A gxgA;

gaoxiaoguang::A gaoxiaoguangA;

gxg::BFunction();

gaoxiaoguang::BFunction();

 

我們寫程式時使用標準的程式庫經常會這樣寫:

#include <iostream>

std::cout << “hello world!” << std::endl;

或者

#include <iostream>

using namespace std;

cout << “hello world!” << endl;

 

這兩句話的差異在於一個使用了using namespace std。”using directive會使namespace內的所有名字曝光。using directive 等於將這些名字宣告於namespace之外。這麼一來,名稱衝突問題就可能死灰複燃。”——《c++標準程式庫》。也就是說,在兩個命名空間都需要用到的時候,而且有重合的時候不能同時使用using namespace gxg和using namespace gaoxiaoguang照樣會出現編譯不通過的問題。

所以說,在使用命名空間的時候盡量不要用相同的名字,即使有相同的名字,最好不要設計到經常同時使用的地方。這個原則是為了避免不必要的衝突。或者是說在用每個函數和類的時候,不要嫌麻煩,全部寫上其命名空間,保證不會出現命名衝突問題。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.