名字空間——你所知道的和你所不知道的

來源:互聯網
上載者:User

名字空間是C++的一個特性,它在大型工程裡能夠為名字衝突提供解決方案,然而很多程式員都忽視了它的使用。

這裡用幾個例子說明以下它的一些用法。

1. using declarations

  它給名字空間中聲明的東西提供一個局部別名;

  namespace A<br />{<br /> int f(int);<br /> int i;<br />} //注意,這裡不需分號</p><p>using A::f; //將A裡的f函數引入;</p><p>int f(int); //全域函數</p><p>int main()<br />{<br /> f(1); //二義性錯誤!<br /> int i; //定義局部變數<br /> using A::i; //錯誤!就像又寫了一行 int i;<br />}

using declarations只引用了之前定義的namespace內的名字,對後面的聲明無效:

namespace A<br />{<br /> class X{}; //#1<br /> int Y(); //#2<br /> int f(double); //#3<br />}</p><p>using A::X; //只是#1<br />using A::Y; //只是#2<br />using A::f; //只是#3</p><p>namespace A<br />{<br /> class Y{}; //#4<br /> int f(int);//#5<br />}</p><p>int main()<br />{<br /> X x; //OK<br /> Y y; //錯誤, #4不可見<br /> f(1); //調用#3!<br />}</p><p>

 

2. using directives

會將整個名字空間內的名字引入,而且能引用到本指令後面定義的namespace內的名字!

namespace A<br />{<br /> class X{};<br /> int f(double);<br />} </p><p>using namespace A; </p><p>void f()<br />{<br /> X x;//A::X<br /> Y y;//ERROR!<br /> f(1);//OK:int f(double)<br />} </p><p>namespace A<br />{<br /> class Y{};<br /> int f(int);<br />}</p><p>int main()<br />{<br /> X x;//A::X<br /> Y y;//A::Y<br /> f(1);//OK:int f(int)<br />}<br />

 

所以,在標頭檔裡堅決不要出現using,避免一些意外的衝突。在CPP裡使用using,也不能出現在include前面。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.