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

    假定多层继承的各类之间的关系如下图。假定派生类不override基类的虚函数,即Base2不override Base1中声明的虚函数vfBase1(),Base3不override Base2中声明的虚函数vfBase2(),Derived不override 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 virtual void vfBase2_1()
        {
            cout << "This is in Base2::vfBase2_1()" << endl;
        }
    };
    class Base3 : public Base2
    {
    public:
        int m_Base3;
        inline virtual void vfBase3_1()
        {
            cout << "This is in Base3::vfBase3_1()" << endl;
        }
    };
    class Derived : public Base3
    {
    public:
        int m_derived;
        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图解如下:

    (注意:单重继承只有一个虚函数表)

  • 相关阅读:
    JPA或Hibernate中的
    mysql如何在一个字段后面加个字符?
    mysql 怎么通过sql语句批量去掉某一个表中某一个字段的多余字符
    MySql怎样去掉某个字段最后的逗号或最后的字
    condition_variable_any
    Python获取本机外网IP
    Ftp download
    5. Abstract Factory
    0. Design Principle
    4. Factory Method
  • 原文地址:https://www.cnblogs.com/wuchanming/p/4091590.html
Copyright © 2011-2022 走看看