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 30 31 32 33 34 35 36 | #include <iostream> class Demo { public : Demo() { std::cout << "constructor called.." << std::endl; count++; } static int getCount() { return count; } private : static int count; }; int Demo::count = 0; int main( void ) { Demo d1; std::cout << Demo::getCount() << std::endl; Demo d2; std::cout << d2.getCount() << std::endl; Demo d3; std::cout << d3.getCount() << std::endl; return 0; } /* 《程式語言教學誌》的範例程式 檔名:classdemo11.cpp 功能:示範 C++ 程式 作者:張凱慶 時間:西元 2013 年 1 月 */ |
count 為 static 成員變數 (member variable)
15 | static int count; |
存取宣告為 static 的成員變數得用 static 的成員函數 (member function)
10 11 12 | static int getCount() { return count; } |
count 用來計算 Demo 物件建立的次數,這必須在類別定義外先初始化
18 | int Demo::count = 0; |
由於 getCount() 為 static 成員函數,因此可以直接用類別名稱呼叫
22 | std::cout << Demo::getCount() << std::endl; |
編譯執行結果如下

中英文術語對照 | |
---|---|
類別 | class |
成員 | member |
物件 | object |
成員變數 | member variable |
成員函數 | member function |
您可以繼續參考
類別
相關目錄
回 C++ 快速導覽
回 C++ 教材
回首頁
參考資料
C++ reference
cplusplus.com
Cprogramming.com C++ Tutorial
C++ Primer, Fourth Edition, Stanley B. Lippman...
沒有留言:
張貼留言