
存取標籤 protected 的成員只限類別中可以使用,這點如同 private ,例如
| 001 | #include <iostream> |
| 002 | |
| 003 | class Demo { |
| 004 | public: |
| 005 | Demo(int pa, int pb) { |
| 006 | a = pa; |
| 007 | b = pb; |
| 008 | } |
| 009 | |
| 010 | int do_something() { |
| 011 | return a + b; |
| 012 | } |
| 013 | |
| 014 | protected: |
| 015 | int a; |
| 016 | int b; |
| 017 | }; |
| 018 | |
| 019 | int main() { |
| 020 | Demo d(12, 10); |
| 021 | std::cout << d.do_something() |
| 022 | << std::endl; |
| 023 | |
| 024 | return 0; |
| 025 | } |
| 026 | |
| 027 | /* Kaiching Chang |
| 028 | u0905.cpp |
| 029 | 2014-02 */ |
Demo 中宣告了兩個 protected 資料成員
| 014 | protected: |
| 015 | int a; |
| 016 | int b; |
另外在 public 的建構函數與 do_something() 使用其值
| 020 | Demo d(12, 10); |
| 021 | std::cout << d.do_something() |
| 022 | << std::endl; |
編譯執行結果如下
| $ g++ u0905.cpp |
| $ ./a.out |
| 22 |
| $ |
繼承機制中, public 與 protected 成員都可被繼承,只有 private 成員不能被繼承。
continue ...
沒有留言:
張貼留言