有重写的单继承
派生类中重写了基类的print()函数。
//Derived_Overwrite.h #pragma once #include "base.h" class Derived_Overrite : public Base { public: Derived_Overrite(int); virtual ~Derived_Overrite(void); virtual void print(void) const; protected: int iDerived; };
//Derived_Overwrite.cpp #include "stdafx.h" #include "Derived_Overwrite.h" Derived_Overrite::Derived_Overrite(int i):Base(0) { iDerived = i; cout<<"Derived_Overwrite::Derived_Overwrite()"<<endl; } Derived_Overrite::~Derived_Overrite(void) { cout<<"Derived_Overwrite::~Derived_Overwrite()"<<endl; } void Derived_Overrite::print(void) const { cout<<"Derived_Overwrite::print(), iDerived " << iDerived << endl; }
Base、Derived_Overwrite的类图如下所示:
重写print()函数在虚函数表中表现如下:
为了验证上述C++对象模型,我们编写如下测试代码。
void test_single_inherit_rewrite() { Derived_Overwrite d(11111); cout << "对象d的起始内存地址:" << &d << endl; cout << "虚函数表地址:" << (int*)(&d) << endl; //虚函数信息 cout << "虚函数表中第1个函数占位符的地址:" << (int*)*(int*)(&d) << "即析构函数在虚函数表中占位符的地址" << endl; cout << "虚函数表中第2个函数占位符的地址:" << ((int*)*(int*)(&d) + 1) << endl; typedef void(*Fun)(void); Fun pFun = (Fun)*((int*)*(int*)(&d) + 1); pFun(); d.print(); cout << endl; cout << "虚函数表中第3个函数占位符的内容:" << *((int*)*(int*)(&d) + 2) << endl; cout << endl; cout << "推测数据成员iBase地址:" << ((int*)(&d) +1) << "通过地址取得的值:" << *((int*)(&d) +1) << endl; cout << "推测数据成员iDerived地址:" << ((int*)(&d) +2) << "通过地址取得的值:" << *((int*)(&d) +2) << endl; }
代码执行结果:
特别注意下,前面的模型虚函数表中最后一项没有打印出来,本实例中共2个虚函数,打印虚函数表第3项为0。其实虚函数表以0x0000000结束,类似字符串以’ ’结束。