代码
先不说废话啦,上代码:
#include<iostream>
#include <stdio.h>
using namespace std;
class B0 {
public:
virtual void vir1() {cout << "B0::vir1" << endl;}
virtual void vir2() {cout << "B0::vir2" << endl;}
};
class B1: public B0 {
public:
virtual void vir1() {cout << "B1::vir1" << endl;}
virtual void barB1() {cout << "B1::bar" << endl;}
virtual void fooB1() {cout << "B1::foo" << endl;}
};
class B2: public B0 {
public:
virtual void vir2() {cout << "B2::vir2" << endl;}
virtual void barB2() {cout << "B2::bar" << endl;}
virtual void fooB2() {cout << "B2::foo" << endl;}
};
class D : public B1, B2 {
public:
void fooB1() {cout << "D::foo" << endl;}
void barB2() {cout << "D::bar" << endl;}
};
typedef void (*Func)();
int test1() {
D tt;
Func* vptr1 = *(Func**)&tt;
Func* vptr2 = *((Func**)&tt + 1);
cout<<"============"<<endl;
vptr1[0]();
vptr1[1]();
vptr1[2]();
vptr1[3]();
vptr1[4]();
cout<<"============"<<endl;
vptr2[0]();
vptr2[1]();
vptr2[2]();
vptr2[3]();
cout<<"============"<<endl;
return 0;
}
输出:
============
B1::vir1
B0::vir2
B1::bar
D::foo
D::bar
============
B0::vir1
B2::vir2
D::bar
B2::foo
============
结论:
多重继承会有多个虚函数表,几重继承,就会有几个虚函数表。这些表按照派生的顺序依次排列,如果子类改写了父类的虚函数,那么就会用子类自己的虚函数覆盖虚函数表的相应的位置,如果子类有新的虚函数,那么就添加到第一个虚函数表的末尾。
用图表示
画了一下图,大概是这样: