代碼
先不說(shuō)廢話啦持钉,上代碼:
#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
============
結(jié)論:
多重繼承會(huì)有多個(gè)虛函數(shù)表,幾重繼承第练,就會(huì)有幾個(gè)虛函數(shù)表阔馋。這些表按照派生的順序依次排列,如果子類改寫了父類的虛函數(shù)娇掏,那么就會(huì)用子類自己的虛函數(shù)覆蓋虛函數(shù)表的相應(yīng)的位置呕寝,如果子類有新的虛函數(shù),那么就添加到第一個(gè)虛函數(shù)表的末尾婴梧。
用圖表示
畫了一下圖下梢,大概是這樣:
image.png