C++[第十一章]--多重继承

文章讨论了多重继承的概念,即一个类可以从多个基类继承特性。然而,这可能导致二义性问题,当不同基类中有相同成员时。为了解决这个问题,文章介绍了虚拟继承的概念,通过创建一个包含公共特性的新基类(如Furniture),让其他类(Sofa和Bed)虚拟继承这个基类,从而消除二义性。示例代码展示了如何在C++中实现这一方案,并通过设置权重展示了一个简单的用例。
摘要由CSDN通过智能技术生成

多重继承

1、从多个基类继承

格式 :

class Sofabed : public Sofa, public Bed {
};

2、问题:二义性

两个基类有同样的成员

3、解决方法(虚拟继承)

1、可以自己强制指定 (不优雅)
s.Sofa::setWeight(100);

4、虚拟继承

1.从Sofa, Bed中取出公共特性,创建新类Furniture: 它含有weight
2.Sofa, Bed虚拟继承Furniture
3.Sofabed多重继承Sofa, Bed

格式: virtual

class Furniture {
private:
	int weight;
public:
	void setWeight(int weight) { this->weight = weight; }
	int getWeight(void) const { return weight; }
};

class Sofa : virtual public Furniture {
private:
	int a;
public:
	void watchTV(void) { cout<<"watch TV"<<endl; }
};

内存情况
在这里插入图片描述
例子:

#include <iostream>
#include <string.h>
#include <unistd.h>

using namespace std;

class Furniture {
private:
	int weight;
public:
	void setWeight(int weight) { this->weight = weight; }
	int getWeight(void) const { return weight; }
};

class Sofa : virtual public Furniture {
private:
	int a;
public:
	void watchTV(void) { cout<<"watch TV"<<endl; }
};

class Bed : virtual public Furniture {
private:
	int b;
public:
	void sleep(void) { cout<<"sleep"<<endl; }
};

class Sofabed : public Sofa, public Bed {
private:
	int c;
};

int main(int argc, char **argv)
{
	Sofabed s;
	s.watchTV();
	s.sleep();

	s.setWeight(100);
	
	return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

起风就扬帆

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

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

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

打赏作者

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

抵扣说明:

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

余额充值