#include <iostream> using namespace std; class A { private: virtual void Func1() { cout << "class A Func1" << endl; } virtual void Func2() { cout << "class A Func2" << endl; } }; class B : public A { public: virtual void Func1() { cout << "class B Func1" << endl; } void Func2() { cout << "class B Func2" << endl; } virtual void Func3() { cout << "class B Func3" << endl; } }; class C { public: virtual void Func1() { cout << "class C Func1" << endl; } virtual void Func3() { cout << "class C Func3" << endl; } virtual void Func4() { cout << "class C Func4" << endl; } }; class D : public B, public C { public: virtual void Func1() { cout << "class D Func1" << endl; } virtual void Func5() { cout << "class D Func5" << endl; } }; int* GetFuncAddr(void* p, int offer) { int* v_ptrAdrs = *((int**)p); // void* pp = p; // __asm mov ecx, pp; return *((int**)v_ptrAdrs + offer); } typedef void (*gFUNC)(); void AFunc1Helper(A *p) { //直接调用虚函数 (*(gFUNC)GetFuncAddr(p, 0))(); } void AFunc2Helper(A *p) { (*(gFUNC)GetFuncAddr(p, 1))(); } //B类中的虚表列表 void BFunc1Helper(B *p) { (*(gFUNC)GetFuncAddr(p, 0))(); } void BFunc2Helper(B *p) { (*(gFUNC)GetFuncAddr(p, 1))(); } void BFunc3Helper(B *p) { (*(gFUNC)GetFuncAddr(p, 2))(); } void CFunc1Helper(C *p) { (*(gFUNC)GetFuncAddr(p, 0))(); } void CFunc4Helper(C *p) { (*(gFUNC)GetFuncAddr(p, 1))(); } //此处,D和B公用一个虚函数表,C单独使用一个虚函数表 void DFunc1Helper(D *p) { (*(gFUNC)GetFuncAddr(p, 0))(); } void DFunc2Helper(D *p) { (*(gFUNC)GetFuncAddr(p, 1))(); } void DFunc3Helper(D *p) { (*(gFUNC)GetFuncAddr(p, 2))(); } void DFunc5Helper(D *p) { (*(gFUNC)GetFuncAddr(p, 3))(); } //C单独使用一个虚函数表 void DCFunc1Helper(D *p) { //此处为第二个虚函数表 int *ptr = (int*)p + 1; (*(gFUNC)GetFuncAddr(ptr, 0))(); } void DCFunc3Helper(D *p) { int *ptr = (int*)p + 1; (*(gFUNC)GetFuncAddr(ptr, 1))(); } void DCFunc4Helper(D *p) { int *ptr = (int*)p + 1; (*(gFUNC)GetFuncAddr(ptr, 2))(); } int _tmain(int argc, _TCHAR* argv[]) { C *pc = new C; D *pd = new D; A *pa = new D; //pa->Func1(); AFunc1Helper(pa); //pa->Func2(); AFunc2Helper(pa); //pc->Func1(); CFunc1Helper(pc); //pc->Func4(); CFunc4Helper(pc); cout << sizeof(D) << endl; pd->Func1(); DFunc1Helper(pd); DFunc2Helper(pd); pd->C::Func3(); DFunc3Helper(pd); DFunc5Helper(pd); DCFunc4Helper(pd); return 0; }