您的位置:首页 > 编程语言 > C语言/C++

深度剖析c++菱形继承!

2017-11-24 23:12 375 查看


菱形继承属于多继承的一种,如图中所示,son继承了father1和father2,属于多继承!

菱形继承的特点:

son将grandfather类继承了两次!

问题提出:

son中,会将grandfather的成员继承几次呢?

看下面例子:

#include <iostream>

using namespace std;

class grandfather{

public:
string _name;
};
class father1 :public grandfather
{

protected:
string _fathername1;
};

class father2 :public grandfather
{
protected:
string _fathername2;
};

class son: public father1, public father2
{
protected:
string _num;
};```

我们可以看出,son应该将grandfather类继承了两次;看下面的菱形继承对象模型:
![菱形继承对象模型](https://img-blog.csdn.net/20171107222453733?watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQvbGl1eGlhb2thaV9saXU=/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/SouthEast)

从图中我们可以看到,son继承了两次grandfather类,因为grandfather中的成员name存在了两份;我们可以创建一个son的对象,借助vs的监视窗口来看看他存在的方式:
![这里写图片描述](https://img-blog.csdn.net/20171107224521696?watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQvbGl1eGlhb2thaV9saXU=/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/SouthEast)

我们可以看到,son创建的对象s中,存在了两个grandfather的成员name,分别存在于father1和father2的对象中。而且在修改时,father1和father2的对象继承于grandfather类的成员,会分别改变。
这样就会引起一个问题,那就是二义性和数据冗余的问题,因为son只需要继承一份grandfather的成员。

这时候我们就引入了虚继承概念,它主要是为了解决这个问题。
![这里写图片描述](https://img-blog.csdn.net/20171124230850249?watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQvbGl1eGlhb2thaV9saXU=/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/SouthEast)


include

using namespace std;

class grandfather{

public:

string _name;

};

class father1 :public virtual grandfather

{

protected:

string _fathername1;

};

class father2 :public virtual grandfather

{

protected:

string _fathername2;

};

class Son: public father1, public father2

{

protected:

int _num;

};

void main()

{

father1 f1();

Son s;

system(“pause”);

“`

如图所示,虚继承引入了一个虚表,每个类都会多出一块空间来存放继承于父类的共有属性的地址偏移量,这样在改动数据时就会改动的为同一个数据。

虚继承:

1:解决了子类对象包含多份父类对象的数据冗余和二义性问题。

2:虚继承体系比较复杂一般不会用到菱形继承的虚继承体,应为带来了性能上的损耗。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: