C++复杂菱形继承

#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;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值