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图解如下:

  • 相关阅读:
    如何用命令将本地项目上传到github
    Mysql基本命令一
    Mysql基本命令二
    PDO操作数据库
    PHP分页
    JQuery中$.ajax()方法参数详解
    基于jquery的has()方法以及与find()方法以及filter()方法的区别详解
    IE浏览器兼容问题
    购物车的实现方式
    JS学习之路
  • 原文地址:https://www.cnblogs.com/wuchanming/p/4091628.html
Copyright © 2011-2022 走看看