验证virtual函数的原理

#include <iostream>
using namespace std;


class Base{
public:
virtual void f() { cout << "the first virtual function f" << endl; }
virtual void g() { cout << "the second virtual function g" << endl; }
virtual void h() { cout << "the third virtual function h" << endl; }

};


#include "Base.h"
#include <iostream>
using namespace std;


typedef void(*Fun)(void);//Fun在这里被定义为一种类型,这个类型可以描述为:指向参数为void,返回值也是void的函数的一个指针


int main(){
Base b;
Fun pFun = NULL;
cout<<"vtable address:"<<(int*)(&b)<<endl;//这里说的vtable是一个指针,即指向数组的指针 int**
cout<<"first virtual function address is"<<(int*)*(int*)(&b)<<endl;
// Invoke the first virtual function
int* vtable = (int*)*(int*)(&b);//int* 标志着vtable数组的开始
pFun = (Fun)*(vtable);
pFun();
cout<<"second virtual function address is"<<(vtable+1)<<endl;
pFun = (Fun)*(vtable+1);
pFun();
cout<<"third virtual function address is"<<(vtable+2)<<endl;
pFun = (Fun)*(vtable+2);
pFun();
}


这里的验证方法是,如果地址不是虚函数的地址,那么用函数指针调用的时候,程序会崩溃,如果没有崩溃得到正确的结果那说明你的运算时正确的。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值