首页 > 代码库 > 对象内存布局 (13)——上一篇的纠正
对象内存布局 (13)——上一篇的纠正
下面来看看虚基类对对象内存布局的影响。虚基类的主要作用就是在所有的派生类中,保留且仅保留一份虚基类的suboject。
#include <iostream>using namespace std;class Base{public: int m_base; Base():m_base(20){} virtual void vfBase_1() { cout << "This is in Base::vfBase_1()" << endl; } virtual void vfBase_2() { cout << "This is in Base::vfBase_2()" << endl; }};class Derived : public virtual Base{public: int m_derived; Derived():m_derived(10){} virtual void vfDerived() { cout << "This is in Derived::vfDerived()" << endl; } void vfBase_1() { cout << "This is in Derived::vfBase_1()" << endl; }};typedef void (*VFun)(void);int main(void){ Derived d; int **pVtab=NULL; pVtab=(int**)&d; cout << "The size of Base object = \t" << sizeof(Derived) << endl; cout << endl; cout<<"derived lst virtual function address: "<<(int*)(*((int*)(*(int*)&d) + 0))<<endl; cout<<"derived lst virtual function result: "; VFun pVF =(VFun)pVtab[0][0]; pVF(); cout<<endl; cout<<"derived 2nd virtual function address: "<<(int*)(*((int*)(*(int*)&d) + 1))<<endl; cout<<"derived 2nd virtual function result: "; pVF = (VFun)pVtab[0][1]; pVF(); cout<<endl; cout<<"virtual table end flags: "<<pVtab[0][2]<<endl; cout<<endl; cout<<"derived data member:"; cout<<(int)*((int*)&d+1)<<endl; cout<<"base lst virtual function address: "<<(int*)pVtab[2][0]<<endl; cout<<"base lst virtual function result: "; pVF = (VFun)pVtab[2][0]; pVF(); cout<<endl; //转换为int*就代表虚函数的地址 cout<<"base 2nd virtual function address: "<<(int*)(*((int*)(*((int*)&d+2)) + 1))<<endl; cout<<"base 2nd virtual function result: "; //转换为vFun代表虚函数的函数指针 pVF = (VFun)(*((int*)(*((int*)&d+2)) + 1)); pVF(); cout<<endl; cout<<"virtual table end flags: "<<(*((int*)(*((int*)&d+2)) + 2))<<endl; cout<<endl; cout<<"base data member:"; cout<<(int)pVtab[3]<<endl; return 0;}
运行结果:
虚继承的内存分布图:
对象内存布局 (13)——上一篇的纠正
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。