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 | #include <iostream> class Demo { public : Demo( int pa, int pb) { a = pa; b = pb; } friend int do_something(Demo& d) { return d.a + d.b; } friend class Demo2; private : int a; int b; }; class Demo2 { public : int do_something2(Demo& d) { return d.a + d.b; } }; int main( void ) { Demo d(32, 22); std::cout << do_something(d) << std::endl; Demo2 d2; std::cout << d2.do_something2(d) << std::endl; return 0; } /* 《程式語言教學誌》的範例程式 檔名:classdemo10.cpp 功能:示範 C++ 程式 作者:張凱慶 時間:西元 2013 年 1 月 */ |
do_something() 為宣告為 friend 的成員函數,注意,這裡以 Demo 的參考 (reference) 當參數 (parameter) ,至於 Demo2 為可存取 Demo private 成員的類別
10 11 12 13 14 | friend int do_something(Demo& d) { return d.a + d.b; } friend class Demo2; |
Demo2 的 do_something2() 以 Demo 的參考當參數,就可以存取 Demo 的 private 成員了
23 24 25 | int do_something2(Demo& d) { return d.a + d.b; } |
friend 成員函數 do_something() 不需要以物件 (object) 呼叫, Demo2 的 do_something2() 則需要用 Demo2 的物件呼叫
29 30 31 32 | Demo d(32, 22); std::cout << do_something(d) << std::endl; Demo2 d2; std::cout << d2.do_something2(d) << std::endl; |
編譯執行結果如下

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