C++ 命名空間

來源:互聯網
上載者:User

標籤:c++

我就是喜歡簡簡單單的表達。


使用命名空間的目的是對標識符的名稱進行本地化,以避免命名衝突。

Namespace 關鍵字的出現就是針對這種問題的。由於這種機制對於聲明於其中的名稱都進行了本地化,就使得相同的名稱可以在不同的上下文中使用,而不會引起名稱的衝突。我們也可以在自己的程式中建立自己的命名空間,這樣可以對我們認為可能導致衝突的名稱進行本地化。這點在我們建立類或者是函數庫的時候是特別重要的。

命名空間基礎

namespace 關鍵字使得我們可以通過建立作用範圍來對全域命名空間進行分隔。本質上來講,一個命名空間就定義了一個範圍。定義命名空間的基本形式如下:

namespace 名稱{//聲明}

在命名空間中定義的任何東西都局限於該命名空間內。

using關鍵字

如果在程式中需要多次引用某個命名空間的成員,那麼按照之前的說法,我們每次都要使用範圍解析符來指定該命名空間,這是一件很麻煩的事情。為瞭解決這個問題,人們引入了using關鍵字。using語句通常有兩種使用方式:

using namespace 命名空間名稱;

using 命名空間名稱::成員;


以上轉載http://blog.chinaunix.net/uid-26874138-id-3215266.html

=============================================================================

檔案:student.h

#include <iostream>using namespace  std;namespace stu {    class student {        public:             student(){};            ~student(){};            int fun(){                cout << "stu" << endl;            }           };}namespace ter {    class student {        public:             student(){};            int fun()               {                       cout << "teacher" << endl;            }           };}


檔案名稱:namespace.cxx 

#include <stdio.h>#include <iostream>#include "student.h"using namespace std;using namespace stu;using namespace ter;int main(void){    stu::student a;    ter::student b;     a.fun();      b.fun();    return 0;}~


總結:一個命名一個空間,內容隨意重複互補幹擾。

本文出自 “自己簡單總結” 部落格,請務必保留此出處http://2714254.blog.51cto.com/2704254/1683760

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.