多重继承下的虚函数表

#include "stdafx.h"
#include
using namespace std;
class Base1
{
private:
  virtual void A() { cout << "Base::A" << endl; }
};
class Base2
{
private:
virtual void B() {cout<<"Base::B"< };
class Derive : public Base1 ,public Base2
{


virtual void C(){cout<<"Derive::C"<

};


typedef void(*Fun)(void);
int _tmain(int argc, _TCHAR* argv[])
{     


//Base1 d;
Derive d;
//d.C(): //私有无法访问
//Fun pFun = (Fun)*((int*)*(int*)(&d)+1);//可以 //通过这种方式访问基类中的私有函数
//d.A();//私有无法访问
//Fun  pFun = (Fun)*((int*)*(int*)(&d)+0);//可以//通过这种方式访问派生类中的私有函数(派生类没有重写(覆盖)基类中的虚函数但可以通过这种方式直接访问)
//pFun();



Base1 b;
//b.f(); //无法访问
Fun  pFun = (Fun)*((int*)*(int*)(&b)+0);//通过这种方式访问基类中的私有函数
pFun(); //可以
system("pause");
return 0;
}

//基类内存模型

多重继承下的虚函数表_第1张图片


派生类内存模型


多重继承下的虚函数表_第2张图片

总结:

1.多继承情况下派生类虚函数表指针分别指向各自的基类的虚函数表。

2.多继承的时候如果子类没有重写基类中的虚函数的情况下,会把子类的虚函数地址加到第一个(按照声明顺序)基类的虚函数表中(按照顺序加到基类虚函数的后面);

3.利用虚函数表可以访问私有成员。



你可能感兴趣的:(内存管理,虚函数,C++,多重载,内存,指针,继承)