详谈C++虚函数表那回事(多重继承关系)

时间:2022-01-16 07:38:12

上一篇说了一般继承,也就是单继承的虚函数表,接下来说说多重继承的虚函数表:

1.无虚函数覆盖的多重继承:

代码:

#pragma once

//无覆盖,多重继承
class Base1
{
public: //三个虚函数
virtual void f() { cout << "Base1::f" << endl; }
virtual void g() { cout << "Base1::g" << endl; }
virtual void h() { cout << "Base1::h" << endl; }
}; class Base2
{
public: //三个虚函数
virtual void f() { cout << "Base2::f" << endl; }
virtual void g() { cout << "Base2::g" << endl; }
virtual void h() { cout << "Base2::h" << endl; }
}; class Base3
{
public: //三个虚函数
virtual void f() { cout << "Base3::f" << endl; }
virtual void g() { cout << "Base3::g" << endl; }
virtual void h() { cout << "Base3::h" << endl; }
}; //多重继承无覆盖
class Derive :public Base1 , public Base2 , public Base3
{
public:
virtual void f1() { cout << "Derive::f1" << endl; }
virtual void g1() { cout << "Derive::g1" << endl; }
virtual void h1() { cout << "Derive::h1" << endl; }
}; void Test()
{
Derive d;
}

调试结果:

详谈C++虚函数表那回事(多重继承关系)

可得:

1》每个父类都有虚表;

2》同样问题,虚表中没有体现出子类的虚函数;见真实内容:

详谈C++虚函数表那回事(多重继承关系)

可见子类的虚函数在按基类声明顺序的第一个基类的虚表中,且在此基类虚函数之后;

2.有虚函数覆盖的多重继承:

代码:

#pragma once

//有虚函数覆盖的多重继承
#pragma once //无覆盖,多重继承
class Base1
{
public: //三个虚函数
virtual void f() { cout << "Base1::f" << endl; }
virtual void g() { cout << "Base1::g" << endl; }
virtual void h() { cout << "Base1::h" << endl; }
}; class Base2
{
public: //三个虚函数
virtual void f() { cout << "Base2::f" << endl; }
virtual void g() { cout << "Base2::g" << endl; }
virtual void h() { cout << "Base2::h" << endl; }
}; class Base3
{
public: //三个虚函数
virtual void f() { cout << "Base3::f" << endl; }
virtual void g() { cout << "Base3::g" << endl; }
virtual void h() { cout << "Base3::h" << endl; }
}; //多重继承无覆盖
class Derive :public Base1, public Base2, public Base3
{
public:
virtual void f() { cout << "Derive::f" << endl; } //唯一一个覆盖的子类函数
virtual void g1() { cout << "Derive::g1" << endl; }
virtual void h1() { cout << "Derive::h1" << endl; }
}; void Test()
{
Derive d; Base1 *b1 = &d;
Base2 *b2 = &d;
Base3 *b3 = &d;
b1->f(); //Derive::f()
b2->f(); //Derive::f()
b3->f(); //Derive::f() b1->g(); //Base1::g()
b2->g(); //Base2::g()
b3->g(); //Base3::g() }

运行结果:

详谈C++虚函数表那回事(多重继承关系)

其实底层是这样的:

详谈C++虚函数表那回事(多重继承关系)

分析:

1》每个父类的虚表中原本存放f()函数的地方,被子类的f()函数覆盖;

2》其余不变;(意思是,还有没被用来覆盖的子类虚函数,任然在首个父类虚函数表的后边位置)

见图:

详谈C++虚函数表那回事(多重继承关系)

赐教!