
最基本的就是把成員變數 (variable member) 封裝 (encapsulation) 在類別之中,這時候就要用到 private 存取標籤 (accsee label) 了
class Demo { public : void setA( int n); void setB( int n); int getA(); int getB(); int do_something(); private : int a; int b; }; |
這裡 a 與 b 已經改放到 private 之後,也由於 a 與 b 都是 private 的,因此另外宣告 public 的 setA() 與 setB() 設定 a 與 b 之值, getA() 與 getB() 取得 a 與 b 之值。
setA() 與 setB() 就是俗稱的 setter ,至於 getA() 與 getB() 是俗稱的 getter 。
因此 setA 、 setB 、 getA 、 getB 的實作很簡單,如下
void Demo::setA( int n) { a = n; } void Demo::setB( int n) { b = n; } int Demo::getA() { return a; } int Demo::getB() { return b; } |
do_something也要稍作改變
int Demo::do_something() { return getA() + getB(); } |
我們寫成一個完整範例,如下
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 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 | #include <iostream> using namespace std; class Demo { public : void setA( int n); void setB( int n); int getA(); int getB(); int do_something(); private : int a; int b; }; int Demo::do_something() { return getA() + getB(); } void Demo::setA( int n) { a = n; } void Demo::setB( int n) { b = n; } int Demo::getA() { return a; } int Demo::getB() { return b; } int main( void ) { Demo t; t.setA(11); t.setB(22); cout << endl; cout << t.do_something() << endl; cout << endl; return 0; } /* 《程式語言教學誌》的範例程式 檔名:classdemo2.cpp 功能:示範 C++ 程式 作者:張凱慶 時間:西元 2012 年 10 月 */ |
編譯執行結果如下

但是這樣設定變數成員還得呼叫 setA 與 setB ,有點麻煩,我們希望宣告 (declare) 時就能夠直接設定,嗯,這用建構子 (constructor) 就可以了。
中英文術語對照 | |
---|---|
類別 | class |
資訊隱藏 | information hiding |
成員變數 | variable member |
封裝 | encapsulation |
存取標籤 | accsee label |
宣告 | declare |
建構子 | constructor |
您可以繼續參考
基礎篇
相關目錄
回 C++ 入門指南
回 C++ 教材目錄
回首頁
參考資料
http://www.cplusplus.com/doc/tutorial/classes/
http://www.cplusplus.com/doc/tutorial/classes2/
2 則留言:
為甚麼要多個getA()和getB()
樓上
因為a, b是private,在class外部不能用他們
getA() 和 getB()是public,程式各處都能用
張貼留言