一個簡單例子讓你瞭解C++命名空間

來源:互聯網
上載者:User

      馬上就要找工作了,最近這段時間非常賣力地複習,據說現在各個公司筆試面試都比較重基礎,於是以前一掃而過的東西,現在開始仔細琢磨了。最近的幾篇文章都是記錄我在複習中遇到的一些比較基礎,但是一直忽略的東西,也希望對需要的童鞋有所協助。

      using namespace std 大家肯定都非常熟悉了,C++標準程式庫中的所有標識符都被定義於一個名為 std 的 namespace 中,由於 namespace 的概念,使用C++標準程式庫的任何標識符時,可以有三種選擇(這裡我突然想到,孔乙己說茴香豆的茴字有四種寫法):

      1、直接指定標識符
      例如,使用 std::cout 而不是 cout 。完整語句: std::cout << 1 << std::endl;

      2、使用using關鍵字
      using std::cout; using std::endl; using std::cin;
      以上程式可以寫成 cout << 1 << endl; 

      3、using namespace std
      最方便的就是使用 using namespace std 。這樣命名空間 std 內定義的所有標識符都有效,就好像它們被聲明為全域變數一樣。那麼以上語句可以寫成如下形式:
      cout << 1 << endl;

      那麼,如果我們自己要定義一個命名空間呢?下面這個簡單地例子清楚地說明了這個過程。

          // name.h
            namespace A
            {
                 int fun();
            }

            namespace B
            {
                 int fun();
            }

          // name.cpp
            #include "name.h"

            int A::fun()
            {
                 return 1;
            }

            int B::fun()
            {
                 return 2;
            }

          // main.cpp
            #include <iostream>
            #include "name.h"

            using namespace std;
            using namespace B;

            void main(void)
            {
                 cout << "result = " << fun() << endl;
            }

      因為使用的是命名空間B, 所以程式的的執行結果是:result = 2。當然,上面提到的3中使用命名空間的方法,都可以試一試。^_^

聯繫我們

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