zoukankan      html  css  js  c++  java
  • 对象内存布局 (10)

    在对象内存布局 (9)基础上做些修改:派生类override基类的虚函数,即Base2 override Base1中声明的虚函数vfBase1(),Base3 override Base1中声明的虚函数vfBase1()和Base2中声明的虚函数vfBase2(), Derived override Base1中声明的虚函数vfBase1()、Base2中声明的虚函数vfBase2()和Base3中声明的虚函数vfBase3()。修改如下:

    #include <iostream>
    using namespace std;
    
    class Base1
    {
    public:
        int m_base1;
        inline virtual void vfBase1_1()
        {
            cout << "This is in Base1::vfBase1_1()" << endl;
        }
    };
    class Base2 : public Base1
    {
    public:
        int m_base2;
        inline  void vfBase1_1()
        {
            cout << "This is in Base2::vfBase1_1()" << endl;
        }
        inline virtual void vfBase2_1()
        {
            cout << "This is in Base2::vfBase2_1()" << endl;
        }
    };
    class Base3 : public Base2
    {
    public:
        int m_Base3;
        inline  void vfBase1_1()
        {
            cout << "This is in Base3::vfBase1_1()" << endl;
        }
        inline  void vfBase2_1()
        {
            cout << "This is in Base3::vfBase2_1()" << endl;
        }
        inline virtual void vfBase3_1()
        {
            cout << "This is in Base3::vfBase3_1()" << endl;
        }
    };
    class Derived : public Base3
    {
    public:
        int m_derived;
        inline  void vfBase1_1()
        {
            cout << "This is in Derived::vfBase1_1()" << endl;
        }
        inline  void vfBase2_1()
        {
            cout << "This is in Derived::vfBase2_1()" << endl;
        }
        inline  void vfBase3_1()
        {
            cout << "This is in Derived::vfBase3_1()" << endl;
        }
        inline virtual void fd()
        {
            cout << "This is in Derived::fd()" << endl;
        }
    };
    typedef void (*VFun)(void);
    template<typename T>
    VFun virtualFunctionPointer(T* b, int i)
    {
        return (VFun)(*((int*)(*(int*)b) + i));
    }
    int main(void)
    {
        Derived d;
        cout << "The size of Derived object = 	" << sizeof(Derived) << endl;
        cout << endl;
        cout << "1st virtual function table: " << endl;
        int i = 0;
        while(virtualFunctionPointer(&d, i))
        {
            VFun pVF = virtualFunctionPointer(&d, i++);
            pVF();
        }
        return 0;
    }

    运行结果:

    Derived对象的memory layout图解如下:

  • 相关阅读:
    tyvj[1087]sumsets
    tyvj[1089]smrtfun
    [bzoj3289]Mato的文件管理
    luogu[2093]零件分组
    luogu[1135]奇怪的电梯
    codevs[1300]文件排版
    luogu[1140]相似基因
    动态规划练习题 胖男孩
    动态规划练习题 汇率
    vijos[1355]车队过桥问题
  • 原文地址:https://www.cnblogs.com/wuchanming/p/4091628.html
Copyright © 2011-2022 走看看