多重继承(继承关系大于一)下对象的内存布局如何呢?
下面给出一个这样的继承关系:
编写代码如下:
class Base1
{
public:
Base1(int a=10,int b=100):ma1(a),mb1(b){}
virtual void b1(){cout<<"Base1::b1()"<<" ";}
virtual void bb1(){cout<<"Base1::bb1()"<<" ";}
virtual void bbb1(){cout<<"Base1::bbb1()"<<" ";}
protected:
int ma1;
int mb1;
};
class Base2
{
public:
Base2(int a2=20,int b2=200):ma2(a2),mb2(b2){}
virtual void b2(){cout<<"Base2::b2()"<<" ";}
virtual void bb2(){cout<<"Base2::bb2()"<<" ";}
virtual void bbb2(){cout<<"Base2::bbb2()"<<" ";}
protected:
int ma2;
int mb2;
};
class Base3
{
public:
Base3(int a3=30,int b3=300):ma3(a3),mb3(b3){}
virtual void b3(){cout<<"Base3::b3()"<<" ";}
virtual void bb3(){cout<<"Base3::bb3()"<<" ";}
virtual void bbb3(){cout<<"Base3::bbb3()"<<" ";}
protected:
int ma3;
int mb3;
};
class Derive:public Base1,Base2,Base3
{
public:
Derive(int c,int d):mc(c),md(d){}
virtual void b1(){cout<<"Derive::b1()"<<" ";}
virtual void bb2(){cout<<"Derive::bb2()"<<" ";}
virtual void bbb3(){cout<<"Derive::bbb3()"<<" ";}
virtual void d(){cout<<"Derive::d()"<<" ";}
protected:
int mc;
int md;
};
定义一个派生类对象d;查看其内存布局:
根据内存布局做如下打印:
typedef void (*Function)(void);//函数指针
int main()
{
Derive d(40,400);
Function pFun=NULL;//定义一个函数指针
cout<<"[0] _vfptr"<<endl;//Base1开始
for(int i=0;i<4;++i)
{
pFun=((Function*)(long**)(*(long*)(&d)))[i];
cout<<" "<<"["<<i<<"]"<<" ";
pFun();
cout<<((long**)(*(long*)&d))[i]<<endl;
}
for(int i=1;i<3;++i)
{
cout<<"["<<i<<"]"<<" "<<((long*)&d)[i]<<endl;
}
cout<<"[3] _vfptr"<<endl;//Base2开始
for(int i=0;i<3;++i)
{
pFun=((Function*)((long**)(*((long*)(&d)+3))))[i];
cout<<" "<<"["<<i<<"]"<<" ";
pFun();
cout<<((long**)(*((long*)(&d)+3)))[i]<<endl;
}
for(int i=4;i<6;++i)
{
cout<<"["<<i<<"]"<<" "<<((long*)&d)[i]<<endl;
}
cout<<"[6] _vfptr"<<endl;//Base3开始
for(int i=0;i<3;++i)
{
pFun=((Function*)(long**)(*((long*)(&d)+6)))[i];
cout<<" "<<"["<<i<<"]"<<" ";
pFun();
cout<<((long**)(*((long*)&d+6)))[i]<<endl;
}
for(int i=7;i<11;++i)
{
cout<<"["<<i<<"]"<<" "<<((long*)&d)[i]<<endl;
}
return 0;
}
打印及调试:
可以发现:
1、虚函数指针的优先级高。总是放在成员变量的最前面。
2、在多重继承下,每个父类都有自己的虚函数表,不进行合并。==》虚函数表只与类型有关。
3、子类独有的成员函数放在第一个虚函数表中。(上面中的Derive::d()函数)。
4、有虚函数时,覆盖的虚函数在表中得到更新。
现在自己画出对象d的内存布局: