C++學習筆記--名稱空間

來源:互聯網
上載者:User

標籤:style   blog   ar   使用   sp   strong   on   div   log   

名稱空間是為了更好的控制名稱的範圍,以管理不同的類庫,避免發生衝突。

1、建立名稱空間

如下,使用namespace關鍵字建立了pers和debts兩個名稱空間。

#ifndef NAMESP_H_#define NAMESP_H_namespace pers{const int LEN = 40;struct Person{char fname[LEN];char lname[LEN];};void GetPerson(Person &);void ShowPerson(const Person &);}namespace debts{using namespace pers;struct Debt{Person name;double amount;};void GetDebts(Debt &);void ShowDebts(const Debt &);double SumDebts(const Debt arr[], int n);}#endif

 名稱空間可以是全域的,也可以位於另一個名稱空間中,但不能位於代碼塊中。

分類:

(1)使用者定義的名稱空間(使用namespace關鍵字)

(2)全域名稱空間 (不定義名稱空間的情況下,都屬於全域名稱空間)

2、使用名稱空間

(1)using聲明

using std::cout;

using pers::Person

using聲明使特定的標識符可用

(2)using編譯指令

using編譯指令使整個名稱空間都可用。

如:

using namespace std;

using namespace pers;

註:

(1)使用using聲明比使用using編譯指令更安全

(2)優先使用域解析操作符(::)或using聲明

(3)對於using聲明,首選將其範圍設定為局部而不是全域。

 

C++學習筆記--名稱空間

聯繫我們

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