C++ 多继承和虚继承

版权声明:博客注明来源即可。 https://blog.csdn.net/u014027680/article/details/83005161

来源:我的博客站 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

猜你喜欢

转载自blog.csdn.net/u014027680/article/details/83005161