虚基类的用法

 1 #include <iostream>
 2 
 3 using namespace std;
 4 
 5 class A
 6 {
 7 private:
 8     int a;
 9 public:
10     A(int x):a(x){}
11     void show() const
12     {
13         cout<<"a: "<<a<<endl;
14     }
15     ~A(){}
16 };
17 class B:virtual public A    //定义虚基类的用法
18 {
19 private:
20     int b;
21 public:
22     B(int x,int y):A(x),b(y){}//子类构造函数必须使用初始化列表(初始化列表在时间性能上比函数体内赋值更有优势,注意这里我用的词是赋值而不是初始化。)
23     void show() const       //show函数将父类的show()覆盖掉,const可以限制当前对象的内容不可改变
24     {
25         cout<<"b: "<<b<<endl;
26     }
27     ~B(){}
28 };
29 class C:virtual public A
30 {
31 private:
32     int c;
33 public:
34     C(int x,int z):A(x),c(z){}
35     void show() const
36     {
37         cout<<"c: "<<c<<endl;
38     }
39     ~C(){}
40 };
41 class D:public B, public C
42 {
43 private:
44     int d;
45 public:
46     D(int x,int y,int z,int h):A(x),B(x,y),C(x,z),d(h){}//首先注意构造函数的写法,直接或间接继承虚基类的所有派生类都必须在构造函数的初始化列表里列出对虚基类的初始化,但是,只有最远派生类的构造函数才调用虚基类的构造函数,也就是说,虚基类的成员(a)只有一份拷贝
47     void show() const
48     {
49         B::show();
50         C::show();
51         cout<<"d: "<<d<<endl;
52     }
53     ~D(){}
54 };
55 
56 int main()
57 {
58     D f(1,2,3,4);
59     f.show();
60     return 0;
61 }
View Code
原文地址:https://www.cnblogs.com/jiu0821/p/4156545.html