KnightOnHorse的博客

追求技术的道路永无止境

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


阅读更多
版权声明:本文为博主原创文章,允许转载,转载请注明出处。 https://blog.csdn.net/KnightOnHourse/article/details/79959044
上一篇C++简单菱形继承
下一篇STL.multimap一对多映射,查询某个键对应的所有值
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

关闭
关闭