#include<iostream>
using namespace std;
//virtual继承基类的好处:
//1、避免保留基类的多个拷贝;
//2、避免二义性
//顶层(第一层)
class CBase{
public:
CBase() : iFoo(1){}
virtual void Fun1(){cout << "CBase::Fun1" << endl;}
virtual void Fun2(){cout << "CBase::Fun2" << endl;}
int iFoo;
};
//中间层(第二层)
class CMid1 : virtual public CBase{
public:
CMid1() : iMid(2){}
virtual void Fun1(){ cout << "CMid1::Fun1" << endl;}
virtual void Fun3(){ cout << "CMid1::Fun3" << endl;}
int iMid;
};
class CMid2 : virtual public CBase{
public:
CMid2() : iMid(2){}
virtual void Fun1(){ cout << "CMid2::Fun1" << endl;}
virtual void Fun3(){ cout << "CMid2::Fun3" << endl;}
int iMid;
};
//底层(第三层)
class CDerived : public CMid1, public CMid2{
public:
CDerived() : iBar(3){}
virtual void Fun1(){ cout << "Derived::Fun1" << endl;}
virtual void Fun4(){ cout << "Derived::Fun4" << endl;}
int iBar;
};
typedef void (*LPFN)();
void VtableFuns(LPFN* lpfnArr)
{
for(int i = 0; lpfnArr[i] != NULL; i++){
cout << "[" << lpfnArr[i] << "] : ";
lpfnArr[i]();
}
}
void main()
{
CDerived oDerived;
cout << "Vtable From CMid1>>>>>>>>>>>>>>>" << endl;
VtableFuns((LPFN*)*((int*)(&oDerived)));
cout << "Vtable From CMid2>>>>>>>>>>>>>>>" << endl;
VtableFuns((LPFN*)*(((int*)&oDerived)+3));
cout << "Vtable From CBase>>>>>>>>>>>>>>>" << endl;
VtableFuns((LPFN*)*(((int*)&oDerived)+8));
cout << endl << ">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>" << endl;
cout << "sizeof(CDerived) = " << sizeof(CDerived) << endl;
int* pInt = (int*)(&oDerived);
for(int i = 0; i < sizeof(CDerived)/sizeof(int); i++){
if(i == 0 || i == 1 || i == 3 || i == 4 || i == 8){
cout << "[" << pInt << "] : " << *pInt << "(" << *((int*)(*pInt)) << ")" << endl;
}
else{
cout << "[" << pInt << "] : " << *pInt << endl;
}
pInt++;
}
cout << "&(oDerived.CMid1::iMid) = " << &(oDerived.CMid1::iMid) << endl;
cout << "&(oDerived.CMid2::iMid) = " << &(oDerived.CMid2::iMid) << endl;
cout << ">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>" << endl;
}
C++复杂菱形继承
最新推荐文章于 2023-11-10 00:55:48 发布