对象内存布局 (9)

来源:互联网 发布:美洲文明知乎 编辑:程序博客网 时间:2024/05/16 09:05

前篇:http://blog.csdn.net/pathuang68/archive/2009/04/23/4102006.aspx

 

假定多层继承的各类之间的关系如下图。假定派生类不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 = /t" << 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图解如下:

 

后篇:http://blog.csdn.net/pathuang68/archive/2009/04/23/4103627.aspx

原创粉丝点击