多繼承中多態的實現

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

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