C++多继承下,派生类对象有几张虚函数表?
我们看下面这个示例:
#include <iostream>
#include <string>
#include <typeinfo>
using namespace std;
class Base1//基类
{
public:
Base1() : x(1) {}
virtual void play() { cout << "Base1::play basketball" << endl; }
virtual void dance() { cout << "Base1::dance dance" << endl; }
private:
int x;
};
class Base2//基类
{
public:
Base2() : y(2) {}
virtual void print() { cout << "Base2::print hello world" << endl; }
private:
int y;
};
class Base3//基类
{
public:
Base3() : z(3) {}
virtual void sing() { cout << "Base3::sing song" << endl; }
private:
int z;
};
class Derived : public Base1, public Base2, public Base3//派生类多继承
{
public:
Derived() : w(4) {}
virtual void play() { cout << "Derived::play basketball" << endl; }
virtual void print() { cout << "Derived::print hello world" << endl; }
virtual void sing() { cout << "Derived::sing song" << endl; }
private:
int w;
};
int main()
{
Base1* p1 = new Derived();
Base2* p2 = new Derived();
Base3* p3 = new Derived();
p1->play();
p2->print();
p3->sing();
p1->dance();
return 0;
}
运行截图:
关于C++多态和继承的知识点,在我的C++专栏有详细的叙述。
我们看今天的重点!
C++多继承下,派生类对象有几张虚函数表?
我们打开VS编译器的工具下的命令行:
执行
cl –d1reportSingleClassLayoutDerived main.cpp
我们可以清楚的看到:派生类对象有三个虚函数表,分别对应于三个基类。
这些东西在编译阶段就生成指令了,哪个类型的基类指针,访问的就是对应的vfptr,找对应的vftable,取虚函数地址,这不是水到渠成的?