c++虚函数表详解(五)

来源:互联网 发布:ab plc编程软件下载 编辑:程序博客网 时间:2024/05/30 04:12

基类和派生类的虚函数同名时,派生类对象的虚函数表如何工作?

#include <iostream>#include <tchar.h>using namespace std;class Human{public:virtual void Print(){cout << _T("Human::Print") << endl;}};class Man: public Human{public:virtual void Print(){cout << _T("Man::Print") << endl;}};int _tmain(int argc, TCHAR argv[], TCHAR envp[]){typedef void(*FUN)();Man Modi;int* AddrOfModiVTable = (int*)(*(int*)(&Modi));FUN pFunc = (FUN)(*AddrOfModiVTable);pFunc();return 0;}

执行结果如下所示:

答案:当基类和派生类存在同名虚函数的时候,派生类对象的虚函数表里原先存储基类虚函数地址的那一项存储的同名的派生类虚函数地址。

换句话说,同名的派生类虚函数地址占据了基类虚函数的地址在派生类虚函数表中的位置。

原创粉丝点击