多重继承的派生类中也有虚函数,那么虚函数表是什么样子的呢?
#include <iostream>
#include <tchar.h>
using namespace std;
class Father
{
public:
virtual void walk()
{
cout << _T("Father::walk") << endl;
}
};
class Mother
{
public:
virtual void speak()
{
cout << _T("Mother::speak") << endl;
}
};
class Son: public Father, public Mother
{
public:
virtual void eat()
{
cout << _T("Son::eat") << endl;
}
};
int _tmain(int argc, TCHAR argv[], TCHAR envp[])
{
Son Modi;
cout << _T("Modi的大小为") << sizeof(Modi) << endl;
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)(*AddrOfModiVTable2);
pFunc();
return 0;
}
上述代码的执行结果如下:
用图片解释如下:
图中省略了虚函数表中的NULL项
子类的虚函数的地址存放在从第一个基类继承而来的虚函数表中,存放的规则仍然是先存放基类的虚函数地址,再存放派生类的虚函数地址。