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

来源:互联网 发布:unity3d中自动寻路 编辑:程序博客网 时间:2024/06/08 18:30

多重继承的派生类中存在和基类同名的虚函数的话,派生类的虚函数表是啥样的呢?

#include <iostream>#include <tchar.h>using namespace std;class Father{public:virtual void walk(){cout << _T("Father::walk") << endl;}virtual void speak(){cout << _T("Father::speak") << endl;}virtual void eat(){cout << _T("Father::eat") << endl;}};class Mother{public:virtual void walk(){cout << _T("Mother::walk") << endl;}virtual void speak(){cout << _T("Mother::speak") << endl;}virtual void eat(){cout << _T("Mother::eat") << endl;}};class Son: public Father, public Mother{public:virtual void speak(){cout << _T("Son::speak") << endl;}virtual void run(){cout << _T("Son::run") << endl;}};int _tmain(int argc, TCHAR argv[], TCHAR envp[]){Son Modi;int* pModi = (int*)(&Modi);int* AddrOfModiVTable1 = (int*)(*pModi);//从Father那里继承的虚函数表int* AddrOfModiVTable2 = (int*)(*(++pModi));//从Mother那里继承的虚函数表typedef void(*FUNC)();FUNC pFunc = (FUNC)(*AddrOfModiVTable1);// 从Father继承的虚函数表的第一项pFunc();pFunc = (FUNC)(*(++AddrOfModiVTable1));// 从Father继承的虚函数表的第二项pFunc();pFunc = (FUNC)(*(++AddrOfModiVTable1));// 从Father继承的虚函数表的第三项pFunc();pFunc = (FUNC)(*(++AddrOfModiVTable1));// 从Father继承的虚函数表的第四项pFunc();pFunc = (FUNC)(*AddrOfModiVTable2); // 从Mother继承的虚函数表的第一项pFunc();pFunc = (FUNC)(*(++AddrOfModiVTable2));// 从Mother继承的虚函数表的第二项pFunc();pFunc = (FUNC)(*(++AddrOfModiVTable2));// 从Mother继承的虚函数表的第三项pFunc();return 0;}

上述代码的执行结果如下图所示:

用图示解释如下:

图中省略了虚函数表中的NULL项

 

我们看到子类的同名虚函数的地址会覆盖所有基类的同名虚函数在虚函数表中的项的内容。

原创粉丝点击