C++ 多继承和虚继承

来源:我的博客站 OceanicKang |《C++ 多继承和虚继承》

  • 虚继承:为了防止派生类进行多继承时,构造函数传参二义性
#include <iostream>

class Jiaju
{
public:
	Jiaju(int length, int width, int height) {
		
		this -> length = length;
		this -> width = width;
		this -> height = height;
		
	}
	
	virtual ~Jiaju() {}
	
	void showSize() {
		
		std::cout << "家具 \n 长:" << this -> length << "\n 宽:" << this -> width << "\n 高:" << this -> height << std::endl;
		
	}
	
protected:
	int length;
	int width;
	int height;
};

class ShaFa : virtual public Jiaju
{
public:
	ShaFa(int length, int width, int height) : Jiaju(length, width, height) {
		
		this -> length = length;
		this -> width = width;
		this -> height = height;
		
	}
	
	~ShaFa() {}
	
	void shafa_showSize() {
		
		std::cout << "沙发 \n 长:" << this -> length << "\n 宽:" << this -> width << "\n 高:" << this -> height << std::endl;
		
	}
};

class Chuang : virtual public Jiaju
{
public:
	Chuang(int length, int width, int height) : Jiaju(length, width, height) {
		
		this -> length = length;
		this -> width = width;
		this -> height = height;
		
	}
	
	~Chuang() {}
	
	void chuang_showSize() {
		
		std::cout << "床 \n 长:" << this -> length << "\n 宽:" << this -> width << "\n 高:" << this -> height << std::endl;
		
	}
};

class ShaFaChuang : public ShaFa, public Chuang
{
public:
	ShaFaChuang(int length, int width, int height) : ShaFa(length, width, height), Chuang(length, width, height), Jiaju(length, width, height) {
		
		this -> length = length;
		this -> width = width;
		this -> height = height;
		
	}
	
	~ShaFaChuang() {}
	
	void shafachuang_showSize() {
		
		std::cout << "shafa床 \n 长:" << this -> length << "\n 宽:" << this -> width << "\n 高:" << this -> height << std::endl;
		
	}
};

int main()
{
	ShaFaChuang shafachuang(100, 200, 300);
	
	shafachuang.showSize();
	shafachuang.shafa_showSize();
	shafachuang.chuang_showSize();
	shafachuang.shafachuang_showSize();
	
	return 0;
}

1.JPG

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值