C++ 一目了然虚基类!
1 #include <IOSTREAM.H> 2 //基类 3 class CBase 4 ...{ 5 protected: 6 int a; 7 public: 8 CBase(int na) 9 ...{ 10 a=na; 11 cout<<"CBase constructor! "; 12 } 13 14 ~CBase()...{cout<<"CBase deconstructor! ";} 15 }; 16 17 //派生类1(声明CBase为虚基类) 18 class CDerive1:virtual public CBase 19 ...{ 20 public: 21 CDerive1(int na):CBase(na) 22 ...{ 23 cout<<"CDerive1 constructor! "; 24 } 25 26 ~CDerive1()...{cout<<"CDerive1 deconstructor! ";} 27 28 int GetA()...{return a;} 29 }; 30 31 //派生类2(声明CBase为虚基类) 32 class CDerive2:virtual public CBase 33 ...{ 34 public: 35 CDerive2(int na):CBase(na) 36 ...{ 37 cout<<"CDerive2 constructor! "; 38 } 39 ~CDerive2()...{cout<<"CDerive2 deconstructor! ";} 40 int GetA()...{return a;} 41 }; 42 43 //子派生类 44 class CDerive12:public CDerive1,public CDerive2 45 ...{ 46 public: 47 CDerive12(int na1,int na2,int na3):CDerive1(na1),CDerive2(na2),CBase(na3) 48 ...{ 49 cout<<"CDerive12 constructor! "; 50 } 51 ~CDerive12()...{cout<<"CDerive12 deconstructor! ";} 52 }; 53 void main() 54 ...{ 55 CDerive12 obj(100,200,300); 56 //得到从CDerive1继承的值 57 cout<<" from CDerive1 : a = "<<obj.CDerive1::GetA(); 58 //得到从CDerive2继承的值 59 cout<<" from CDerive2 : a = "<<obj.CDerive2::GetA()<<endl<<endl; 60 }
从上例可以看出,在类CDerived12的构造函数初始化表中,调用了间接基类CBase的构造函数,这对于非虚基类是非法的,但对于虚基类则是合法且必要的。
对于派生类CDerived1和CDerived2,不论是其内部实现,还是实例化的对象,基类CBase是否是它们的虚基类是没有影响的。受到影响的是它们的派生类CDerived12,因为它从两条路径都能到达CBase。
本文来自CSDN博客,转载请标明出处:http://blog.csdn.net/livelylittlefish/archive/2008/03/11/2171267.aspx
博客园的文章都是大学时写的,质量不太好。
我的新文章都会发布再新的 blog :https://blog.biyongyao.com
请大家关注哟!!