注意對介面的繼承須加一個 virtual
1 #include <iostream>
2
3 using namespace std;
4
5 // 介面
6 class IBase
7 {
8 public:
9 IBase(){}
10 virtual ~IBase(){}
11
12 virtual void F1() = 0; // 宣告一個虛擬函數
13 };
14
15 // IBase 的實作類別
16 class CDerived1:virtual public IBase
17 {
18 public:
19 CDerived1(){};
20 ~CDerived1(){};
21
22 virtual void F1() // 實作
23 {
24 cout << "CDerived1::F1" << endl;
25 }
26 };
27
28 // IBase 的延伸介面
29 class IBase2:virtual public IBase
30 {
31 public:
32 IBase2(){};
33 ~IBase2(){};
34
35 virtual void F2() = 0; // 增加宣告一個虛擬函數
36 };
37
38 // IBase2 的實作類別,也是 CDerived1 的延伸類別,
39 // 所以省去了對 IBase 的實作
40 class CDerived2:virtual public IBase2, public CDerived1
41 {
42 public:
43 CDerived2(){};
44 ~CDerived2(){};
45
46 virtual void F2() // 實作
47 {
48 cout << "CDerived2::F2" << endl;
49 }
50 };
51
52
53 int main()
54 {
55 IBase *pIBase = new CDerived2;
56
57 pIBase->F1();
58
59 return 0;
60 }
沒有留言:
張貼留言