关于虚继承的介绍可以看这个网课菱形继承,下面我将介绍虚继承和虚函数对象大小的问题。以下测试是在Visual Studio2017版本下测试,Debug为x64
#include <iostream>
using namespace std;
class Animal{
public:
int m_Age;
};
class Sheep : virtual public Animal {
public:
virtual void print() {
cout << "are you ok" << endl;
}
};
class Camel : virtual public Animal{
public:
virtual void print() {
cout << "are you ok" << endl;
}
};
class Sheep_Camel : public Sheep, public Camel{
public:
void print() {
cout << "I am ok" << endl;
}
};
int main(){
Animal animal;
Sheep sheep;
Camel camel;
Sheep_Camel sheep_camel;
cout << "animal size : " << sizeof(animal) << endl;
//4,只有一个int,4字节
cout << "sheep size : " << sizeof(sheep) << endl;
//24,一个int(4字节),一个vbptr(virtual base pointer)8字节,
//一个vfptr(virtual function pointer)8字节,内存对齐,所以变成24字节
cout << "camel size : " << sizeof(camel) << endl;
//24,一个int(4字节),一个vbptr(virtual base pointer)8字节,
//一个vfptr(virtual function pointer)8字节,内存对齐,所以变成24字节
cout << "sheep_camel size : " << sizeof(sheep_camel) << endl;
//24,一个int(4字节),两个vbptr(virtual base pointer)16字节,
//两个vfptr(virtual function pointer)16字节,分别是base sheep和base camel,
//内存对齐,所以变成40字节
return 0;
}
1>------ 已启动生成: 项目: Project1, 配置: Debug x64 ------
1>hello.cpp
1>
1>class Sheep size(20):
1> +---
1> 0 | {vfptr}
1> 8 | {vbptr}
1> +---
1> +--- (virtual base Animal)
1>16 | m_Age
1> +---
1>
1>Sheep::$vftable@:
1> | &Sheep_meta
1> | 0
1> 0 | &Sheep::print
1>
1>Sheep::$vbtable@:
1> 0 | -8
1> 1 | 8 (Sheepd(Sheep+8)Animal)
1>
1>Sheep::print this adjustor: 0
1>vbi: class offset o.vbptr o.vbte fVtorDisp
1> Animal 16 8 4 0
1>
1>class Sheep_Camel size(36):
1> +---
1> 0 | +--- (base class Sheep)
1> 0 | | {vfptr}
1> 8 | | {vbptr}
1> | | <alignment member> (size=4)
1> | +---
1>16 | +--- (base class Camel)
1>16 | | {vfptr}
1>24 | | {vbptr}
1> | | <alignment member> (size=4)
1> | +---
1> +---
1> +--- (virtual base Animal)
1>32 | m_Age
1> +---
1>
1>Sheep_Camel::$vftable@Sheep@:
1> | &Sheep_Camel_meta
1> | 0
1> 0 | &Sheep_Camel::print
1>
1>Sheep_Camel::$vftable@Camel@:
1> | -16
1> 0 | &thunk: this-=16; goto Sheep_Camel::print
1>
1>Sheep_Camel::$vbtable@Sheep@:
1> 0 | -8
1> 1 | 24 (Sheep_Cameld(Sheep+8)Animal)
1>
1>Sheep_Camel::$vbtable@Camel@:
1> 0 | -8
1> 1 | 8 (Sheep_Cameld(Camel+8)Animal)
1>
1>Sheep_Camel::print this adjustor: 0
1>vbi: class offset o.vbptr o.vbte fVtorDisp
1> Animal 32 8 4 0
下图是运行结果