#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 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;
}
};
int* GetFuncAddr(void* p, int offer)
{
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))();
}
//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))();
}
int _tmain(int argc, _TCHAR* argv[])
{
A *pa = new B;
B *pb = new B;
//通過這種形式,可以非常清晰的看到多態的實現
//pa->Func1();
AFunc1Helper(pa);
//pa->Func2();
AFunc2Helper(pa);
//pb->Func1();
BFunc1Helper(pb);
//pb->Func2();
BFunc2Helper(pb);
//pb->Func3();
BFunc3Helper(pb);
return 0;
}
多態是如何實現的
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.