C++中的菱形继承深入分析

菱形继承

class Person {   int _AA; }; class Student:public Person {   int _BB; }; class Teacher :public Person {   int _CC; }; class Assistant :public Student, public Teacher {   int _DD; }; 

PS:

Assistant的对象中存在两份Person成员

菱形继承存在二义性和数据冗余

解决:

使用虚继承

首先不使用虚继承时:

#include<iostream> using namespace std;  class AA { public:   string _aa; }; class BB :public AA { public:   int _bb; }; class CC :public AA { public:   int _cc; }; class DD :public BB, public CC { public:   int _dd; };  int main() {   DD d;   d.BB::_aa = 1;   d.CC::_aa = 2;   d._bb = 3;   d._cc = 4;   d._dd = 5;   cout << sizeof(d) << endl;   return 0; } 

菱形继承对象模型:

使用虚继承时:

#include<iostream> using namespace std;  class AA { public:   string _aa; }; class BB :<span style="color:#FF0000;">virtual</span> public AA { public:   int _bb; }; class CC :<span style="color:#FF0000;">virtual</span> public AA { public:   int _cc; }; class DD :public BB, public CC { public:   int _dd; };  int main() {   DD d;   d.BB::_aa = 1;   d.CC::_aa = 2;   d._bb = 3;   d._cc = 4;   d._dd = 5;   cout << sizeof(d) << endl;   return 0; }

菱形虚拟继承对象模型:

两个空格处地址相差为8,第一个空格处存放空格处位置到AA的偏移量为20,第二个空格处存放空格处位置到AA的偏移量为12,浪费两个空间存放偏移量,AA只需计算一次。

PS:

1.虚继承解决了在菱形继承体系里面子类对象包含多份父类对象的数据冗余&浪费空间的问题。

2.虚继承体系看起来好复杂,在实际应用我们通常不会定义如此复杂的继承体系。一般不到万不得已都不要定义菱形结构的虚继承体系结构,因为使用虚继承解决数据冗余问题也带来了性能上的损耗。

感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!

飞机一阵抖动,我终于说出了最后一句再见。

C++中的菱形继承深入分析

相关文章:

你感兴趣的文章:

标签云: