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++多继承下,派生类对象有几张虚函数表?
我们打开VS编译器的工具下的命令行,进入代码目录;执行:
cl –d1reportSingleClassLayoutDerived main.cpp
派生类对象有3个虚函数指针,三个虚函数表,分别对应于三个基类。