C++虚函数表理解

#include "iostream"
using namespace std;
class Base1{
public:
	virtual void f(){cout <<"Base1::f" <<endl;}
	virtual void g(){cout <<"Base1::g" <<endl;}
	virtual void h(){cout <<"Base1::h" <<endl;}
};

class Base2{
public:
	virtual void f(){cout <<"Base2::f" <<endl;}
	virtual void g(){cout <<"Base2::g" <<endl;}
	virtual void h(){cout <<"Base2::h" <<endl;}
};

class Base3{
public:
	virtual void f(){cout <<"Base3::f" <<endl;}
	virtual void g(){cout <<"Base3::g" <<endl;}
	virtual void h(){cout <<"Base3::h" <<endl;}
};

class Derive : public Base1, public Base2, public Base3{
public:
	virtual void f(){cout <<"Derive::f" <<endl;}
	virtual void g1(){cout <<"Derive::g1" <<endl;}
	virtual void h1(){cout <<"Derive::h1" <<endl;}
};

typedef void(*Fun)(void);

int main()
{
	Fun pFun = NULL;
	Derive d;
	int** pVtab = (int**)&d;
	cout <<"虚函数表地址:" <<(int*)&d <<endl;

	/* Base1's vtable */
	//pFun = (Fun)*((int*)*((int*)&d + 0) + 0);
	pFun = (Fun)pVtab[0][0];
	pFun();
	//pFun = (Fun)*((int*)*((int*)&d + 0) + 1);
	pFun = (Fun)pVtab[0][1];
	pFun();
	//pFun = (Fun)*((int*)*((int*)&d + 0) + 2);
	pFun = (Fun)pVtab[0][2];
	pFun();
	//pFun = (Fun)*((int*)*((int*)&d + 0) + 3);
	pFun = (Fun)pVtab[0][3];
	pFun();
	//pFun = (Fun)*((int*)*((int*)&d + 0) + 4);
	pFun = (Fun)pVtab[0][4];
	pFun();
	/* Base2's vtable */
	//pFun = (Fun)*((int*)*((int*)&d + 1) + 0);
	pFun = (Fun)pVtab[1][0];
	pFun();
	//pFun = (Fun)*((int*)*((int*)&d + 1) + 1);
	pFun = (Fun)pVtab[1][1];
	pFun();
	//pFun = (Fun)*((int*)*((int*)&d + 1) + 2);
	pFun = (Fun)pVtab[1][2];
	pFun();
	/* Base3's vtable */
	//pFun = (Fun)*((int*)*((int*)&d + 2) + 0);
	pFun = (Fun)pVtab[2][0];
	pFun();
	//pFun = (Fun)*((int*)*((int*)&d + 2) + 1);
	pFun = (Fun)pVtab[2][1];
	pFun();
	//pFun = (Fun)*((int*)*((int*)&d + 2) + 2);
	pFun = (Fun)pVtab[2][2];
	pFun();
	return 0;
}

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值