类和对象-继承-菱形继承

黑马程序员的老师总是能给我一点震撼.

我是李承真,坚持日更,明天,你们就会看到十篇新的笔记

先来个图

不好意思放错了,是这张:

代码1:引出问题

#include<iostream>
using namespace std;

class Animal {
public:
	int m_age;
};
class sheep :public Animal{};
class Tuo :public Animal{};
class sheeptuo :public sheep, public Tuo{};
void test01() {
	sheeptuo st;
	/*st.m_age = 18;*/    // 报错,m_age从"🐏"和"tuo"里面继承,意义不明确
	st.sheep::m_age = 18;
	st.Tuo::m_age = 28;//菱形继承,当父类拥有相同的数据,需要加作用域以区分
	cout << st.sheep::m_age << endl << st.Tuo::m_age << endl;
}//这份数据我们知道,只有一份就可以.

代码2:解决问题

#include<iostream>
using namespace std;

class Animal
{
public:
	int m_age;
};

//利用虚继承,解决菱形继承的问题
//继承之前,加上关键字virtual百年未虚继承
//Animal类 成为 虚基类

class sheep :virtual public Animal{};

class Tuo :virtual public Animal{};

class sheeptuo :public sheep, public Tuo{};

void test01() {
	sheeptuo st;
	st.sheep::m_age = 18;
	st.Tuo::m_age = 28;
	cout << st.m_age;//现在不报错了
	cout << st.sheep::m_age << endl << st.Tuo::m_age << endl;
}

int main() {
	test01();
}

  • 16
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

青樱部_OFFICIAL

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值