C++中菱形继承的示例分析-成都快上网建站

C++中菱形继承的示例分析

这篇文章主要为大家展示了“C++中菱形继承的示例分析”,内容简而易懂,条理清晰,希望能够帮助大家解决疑惑,下面让小编带领大家一起研究并学习一下“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; 
};

C++中菱形继承的示例分析

PS:

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

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

解决:

使用虚继承

首先不使用虚继承时:

#include 
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; 
}

C++中菱形继承的示例分析

菱形继承对象模型:

C++中菱形继承的示例分析

使用虚继承时:

#include 
using namespace std; 
 
class AA 
{ 
public: 
  string _aa; 
}; 
class BB :virtual public AA 
{ 
public: 
  int _bb; 
}; 
class CC :virtual 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; 
}

C++中菱形继承的示例分析

菱形虚拟继承对象模型:

C++中菱形继承的示例分析

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

以上是“C++中菱形继承的示例分析”这篇文章的所有内容,感谢各位的阅读!相信大家都有了一定的了解,希望分享的内容对大家有所帮助,如果还想学习更多知识,欢迎关注创新互联行业资讯频道!


标题名称:C++中菱形继承的示例分析
路径分享:http://kswjz.com/article/ihccop.html
扫二维码与项目经理沟通

我们在微信上24小时期待你的声音

解答本文疑问/技术咨询/运营咨询/技术建议/互联网交流