再谈带有虚函数的类对象之内存结构

来源:互联网 发布:淘宝客服简历自我评价 编辑:程序博客网 时间:2024/05/16 10:06

前篇:http://blog.csdn.net/pathuang68/archive/2009/04/21/4096521.aspx

 

下面的代码中,类Base中定义了两个虚函数vfBase_1()和vfBase_2(),另外还定义了一个整形成员变量m_base;

#include <iostream>

using namespace std;

 

class Base

{

public:

         int m_base;

         inline virtual void vfBase_1()

         {

                   cout << "This is in Base::vfBase_1()" << endl;

         }

 

         inline virtual void vfBase_2()

         {

                   cout << "This is in Base::vfBase_2()" << endl;

         }

};

 

// 定义一个函数指针类型,返回值类型为void,参数类型为void

typedef void (*VFun)(void);

 

// 获取虚函数表中的虚函数指针,其中b为带有虚函数的类的对象的地址,i为虚函数表中虚函数的顺序

VFun virtualFunctionPointer(Base* b, int i)

{

         return (VFun)(*((int*)(*(int*)b) + i));

}

 

int main(void)

{

         Base b;

         cout << "The size of Base object = /t" << sizeof(Base) << endl;

 

         cout << endl;

 

         int i = 0;

         while(virtualFunctionPointer(&b, i))   // 对于VC++编译器,虚函数表最后一项是null

         {

                   VFun pVF = virtualFunctionPointer(&b, i++);

                   pVF();

         }

         return 0;

}

运行结果为:

 

类Base的对象的memory layout如下图: