多继承中多态的实现

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值