模擬編譯器對虛函數索引項的實現

#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;
}


 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章