
衍生類別可以繼承超過一個的基礎類別,這樣的特性被稱為多重繼承 (multiple inheritance) 。
舉例如下
| 001 | #include <iostream> |
| 002 | |
| 003 | class Demo { |
| 004 | public: |
| 005 | Demo() { |
| 006 | a = 702; |
| 007 | b = 631; |
| 008 | } |
| 009 | |
| 010 | protected: |
| 011 | int a; |
| 012 | int b; |
| 013 | }; |
| 014 | |
| 015 | class Demo2 { |
| 016 | public: |
| 017 | Demo2() { |
| 018 | c = 548; |
| 019 | d = 255; |
| 020 | } |
| 021 | |
| 022 | protected: |
| 023 | int c; |
| 024 | int d; |
| 025 | }; |
| 026 | |
| 027 | |
| 028 | class Demo3: Demo, Demo2 { |
| 029 | public: |
| 030 | int do_something() { |
| 031 | return a + b + c + d; |
| 032 | } |
| 033 | }; |
| 034 | |
| 035 | int main(void) { |
| 036 | Demo3 d; |
| 037 | std::cout << d.do_something() |
| 038 | << std::endl; |
| 039 | |
| 040 | return 0; |
| 041 | } |
| 042 | |
| 043 | /* Kaiching Chang |
| 044 | u0918.cpp |
| 045 | 2014-02 */ |
Demo3 繼承自 Demo 與 Demo2 ,用逗號 , 間隔兩個類別
| 028 | class Demo3: Demo, Demo2 { |
| 029 | public: |
| 030 | int do_something() { |
| 031 | return a + b + c + d; |
| 032 | } |
| 033 | }; |
編譯執行,結果如下
| $ g++ u0918.cpp |
| $ ./a.out |
| 2136 |
| $ |
continue ...
沒有留言:
張貼留言