一目了然c++虚基类!

 #include <IOSTREAM.H>
//基类
class CBase
...{
protected:
int a;
public:
CBase(int na)
...{
a=na;
cout<<"CBase constructor! ";
} ~CBase()...{cout<<"CBase deconstructor! ";}
}; //派生类1(声明CBase为虚基类)
class CDerive1:virtual public CBase
...{
public:
CDerive1(int na):CBase(na)
...{
cout<<"CDerive1 constructor! ";
} ~CDerive1()...{cout<<"CDerive1 deconstructor! ";} int GetA()...{return a;}
}; //派生类2(声明CBase为虚基类)
class CDerive2:virtual public CBase
...{
public:
CDerive2(int na):CBase(na)
...{
cout<<"CDerive2 constructor! ";
}
~CDerive2()...{cout<<"CDerive2 deconstructor! ";}
int GetA()...{return a;}
}; //子派生类
class CDerive12:public CDerive1,public CDerive2
...{
public:
CDerive12(int na1,int na2,int na3):CDerive1(na1),CDerive2(na2),CBase(na3)
...{
cout<<"CDerive12 constructor! ";
}
~CDerive12()...{cout<<"CDerive12 deconstructor! ";}
};
void main()
...{
CDerive12 obj(,,);
//得到从CDerive1继承的值
cout<<" from CDerive1 : a = "<<obj.CDerive1::GetA();
//得到从CDerive2继承的值
cout<<" from CDerive2 : a = "<<obj.CDerive2::GetA()<<endl<<endl;
}

从上例可以看出,在类CDerived12的构造函数初始化表中,调用了间接基类CBase的构造函数,这对于非虚基类是非法的,但对于虚基类则是合法且必要的。
  对于派生类CDerived1和CDerived2,不论是其内部实现,还是实例化的对象,基类CBase是否是它们的虚基类是没有影响的。受到影响的是它们的派生类CDerived12,因为它从两条路径都能到达CBase。

一目了然c++虚基类!

本文来自CSDN博客,转载请标明出处:http://blog.csdn.net/livelylittlefish/archive/2008/03/11/2171267.aspx

上一篇:转 在Qt中用QAxObject来操作Excel


下一篇:Asp.Net 上传图片并生成高清晰缩略图