C++ 快速導覽 - 無名命名空間

命名空間 (namespace) 可以是無名的,也就是不帶任何識別字 (identifier) 。



舉例如下
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
#include <iostream>
 
namespace {
    class Demo {
    public:
        int a;
        int b;
     
        int do_something() {
            return a + b;
        }
    };
}
 
int main(void) {
    Demo d;
    d.a = 55;
    d.b = 66;
    std::cout << d.do_something() << std::endl;
 
    return 0;
}
 
/* 《程式語言教學誌》的範例程式
    檔名:namedemo02.cpp
    功能:示範 C++ 程式
    作者:張凱慶
    時間:西元 2013 年 1 月 */


我們在無名命名空間裡頭定義 Demo 類別 (class)
3
4
5
6
7
8
9
10
11
12
13
namespace {
    class Demo {
    public:
        int a;
        int b;
     
        int do_something() {
            return a + b;
        }
    };
}


每個檔案只能有一個無名的命名空間,就直接使用裡頭的識別字
16
Demo d;


同樣的,每個命名空間也只能有一個無名的命名空間。


編譯執行結果如下



中英文術語對照
命名空間namespace
識別字identifier


您可以繼續參考
命名空間
標頭檔與實作檔


相關目錄
回 C++ 快速導覽
回 C++ 教材
回首頁


參考資料
C++ reference
cplusplus.com
Cprogramming.com C++ Tutorial

C++ Primer, Fourth Edition, Stanley B. Lippman...

沒有留言: