验证virtual函数的原理

来源:互联网 发布:淘宝多个客服怎么登陆 编辑:程序博客网 时间:2024/06/05 04:35
#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();
}


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

原创粉丝点击