模拟编译器对虚函数索引项的实现

来源:互联网 发布:俄罗斯女孩中国人知乎 编辑:程序博客网 时间:2024/06/05 15:29
#include <iostream>using namespace std;class A{public:virtual void Func1(){cout << "class A Func1" << endl;}virtual void Func2(){cout << "class A Func2" << endl;}};class B{public:virtual void Func1(){cout << "class B Func1" << endl;}void Func2(){cout << "class B Func2" << endl;}virtual void Func3(){cout << "class B Func3" << endl;}};int* GetFuncAddr(void* p, int offer){//p相当于this指针,off表示虚函数表索引项int* v_ptrAdrs = *((int**)p);return *((int**)v_ptrAdrs + offer);}typedef void (*gFUNC)();void AFunc1Helper(A *p){//直接调用虚函数(*(gFUNC)GetFuncAddr(p, 0))();}//为每一个虚函数,实现一个辅助函数,用于指定虚函数表中的索引项void AFunc2Helper(A *p){        (*(gFUNC)GetFuncAddr(p, 1))();}void BFunc1Helper(B *p){(*(gFUNC)GetFuncAddr(p, 0))();}void BFunc3Helper(B *p){(*(gFUNC)GetFuncAddr(p, 1))();}int _tmain(int argc, _TCHAR* argv[]){A *pa = new A;B *pb = new B;//交换AB虚表指针int v_ptr = *((int*)pa);*((int*)pa) = *((int*)pb);*((int*)pb) = v_ptr;//pa->Func1();AFunc1Helper(pa);//pa->Func2();AFunc2Helper(pa);//pb->Func1();BFunc1Helper(pb);pb->Func2();//pb->Func3();BFunc3Helper(pb);return 0;}


 

原创粉丝点击