#include#include using namespace std; class CAnimal; typedef void (CAnimal::*PFN_FUNC)(void); class CAnimal { public: // 定义两个成员函数指针分别指向两个函数 PFN_FUNC m_pfnEat; PFN_FUNC m_pfnBark; CAnimal(){ this->m_pfnEat = &CAnimal::Eat; this->m_pfnBark = &CAnimal::Bark; } void Eat(){ cout << "Animal Eat()" << endl; } void Bark() { cout << "Animal Bark()" << endl; } }; class CCat :public CAnimal { public: CCat() { this->m_pfnEat = (PFN_FUNC)&CCat::Eat; this->m_pfnBark = (PFN_FUNC)&CCat::Bark; } void Eat() { cout << "喵吃老鼠" << endl; } void Bark() { cout << "我们一起学喵叫" << endl; } }; class CMouse :public CAnimal { public: CMouse() { this->m_pfnEat = (PFN_FUNC)&CMouse::Eat; this->m_pfnBark = (PFN_FUNC)&CMouse::Bark; } void Eat() { cout << "老鼠吃奶酪" << endl; } void Bark() { cout << "老鼠吱吱叫" << endl; } }; int main() { { CAnimal* aryAnimals[] = { new CCat, new CMouse, new CMouse }; for(int i = 0; i < sizeof(aryAnimals)/sizeof(aryAnimals[0]);i++){ (aryAnimals[i]->*aryAnimals[i]->m_pfnEat)(); (aryAnimals[i]->*aryAnimals[i]->m_pfnBark)(); } for (int i = 0; i < sizeof(aryAnimals) / sizeof(aryAnimals[0]); i++) { delete aryAnimals[i]; } } system("pause"); return 0; } #include #include using namespace std; class CAnimal; typedef void (CAnimal::*PFN_FUNC)(void); class CAnimal { public: // 定义一个函数指针 指向保存所有函数地址的数组 PFN_FUNC* __vfptr; CAnimal(){ this->__vfptr = __vtable_animal; } void Eat(){ cout << "Animal Eat()" << endl; } void Bark() { cout << "Animal Bark()" << endl; } // 全局函数指针数组 static PFN_FUNC __vtable_animal[2]; }; // 静态变量初始化 PFN_FUNC CAnimal::__vtable_animal[2] = { &CAnimal::Eat,&CAnimal::Bark }; class CCat :public CAnimal { public: CCat() { // 修改函数指针的指向 指向自己的函数地址表 this->__vfptr = __vtable_cat; } void Eat() { cout << "喵吃老鼠" << endl; } void Bark() { cout << "我们一起学喵叫" << endl; } // 全局函数指针数组 static PFN_FUNC __vtable_cat[2]; }; // 静态变量初始化 PFN_FUNC CCat::__vtable_cat[2] = { (PFN_FUNC)&CCat::Eat,(PFN_FUNC)&CCat::Bark }; class CMouse :public CAnimal { public: CMouse() { // 修改函数指针的指向 指向自己的函数地址表 this->__vfptr = __vtable_mouse; } void Eat() { cout << "老鼠吃奶酪" << endl; } void Bark() { cout << "老鼠吱吱叫" << endl; } // 全局函数指针数组 static PFN_FUNC __vtable_mouse[2]; }; // 静态变量初始化 PFN_FUNC CMouse::__vtable_mouse[2] = { (PFN_FUNC)&CMouse::Eat,(PFN_FUNC)&CMouse::Bark }; int main() { { CAnimal* aryAnimals[] = { new CCat, new CMouse, new CMouse }; for(int i = 0; i < sizeof(aryAnimals)/sizeof(aryAnimals[0]);i++){ (aryAnimals[i]->*aryAnimals[i]->__vfptr[0])(); (aryAnimals[i]->*aryAnimals[i]->__vfptr[1])(); } for (int i = 0; i < sizeof(aryAnimals) / sizeof(aryAnimals[0]); i++) { delete aryAnimals[i]; } } system("pause"); return 0; }



