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个虚函数指针,三个虚函数表,分别对应于三个基类。
该博客讨论了C++中多继承情况下派生类对象的虚函数表数量。通过一个示例代码展示了派生类Derived从Base1、Base2和Base3三个基类继承,并且每个基类都有虚函数。在Visual Studio的编译器工具中,使用-d1reportSingleClassLayoutDerived选项揭示了派生类对象拥有三个虚函数指针,对应基类的每个虚函数表。

8572

被折叠的 条评论
为什么被折叠?



