c++----练习题---沙发类虚基类

6-15 沙发床-虚基类 (10分)

根据给出的Furniture类以及SleeperSofa类,定义SleeperSofa继承时的父类Bed和Sofa

Furniture 类与测试程序的定义如下:

#include<iostream>
using namespace std;

class Furniture
{
	protected:
		int weight ;
	public:
		Furniture(){}
		void setWeight( int i ){ weight= i ;}
		int getWeight() { return weight; }
};

/* 请在这里填写答案 */

class SleeperSofa :public Bed,public Sofa
{
public:
	SleeperSofa() {}
	void foldout()
	{
		cout<<"Fold out sleepersofa"<<endl;
	}
};
int main()
{
	SleeperSofa ss;
	ss.setWeight(20);
	cout<< ss.getWeight()<<endl;
	ss.sleep();
	ss.watchTV();
	ss.foldout(); 
	return 0;
}

输入样例:

输出样例:

在这里给出相应的输出。例如:

20
Sleeping
Watching TV
Fold out sleepersofa

代码实现:

class Bed:virtual public Furniture{//虚基类的基本写法
	public:
		Bed()//一定要有这个,因为有无参函数,下面也是
		{
			
		}
	void sleep()
	{
		cout<<"Sleeping"<<endl;
	}
};
class Sofa:virtual public Furniture{
	public:
		void watchTV()
	{
		cout<<"Watching TV"<<endl;
	}
	Sofa()
	{
		
	}
};

 

好的,以下是家具沙发、床沙发的实现: ```cpp #include <iostream> #include <string> using namespace std; class Furniture { protected: double length; double width; double height; public: Furniture(double l, double w, double h): length(l), width(w), height(h) {} virtual void showInfo() { cout << "Length: " << length << ", Width: " << width << ", Height: " << height << endl; } }; class Sofa : virtual public Furniture { protected: string color; public: Sofa(double l, double w, double h, string c): Furniture(l, w, h), color(c) {} void showInfo() { Furniture::showInfo(); cout << "Color: " << color << endl; } }; class Bed : virtual public Furniture { protected: string material; public: Bed(double l, double w, double h, string m): Furniture(l, w, h), material(m) {} void showInfo() { Furniture::showInfo(); cout << "Material: " << material << endl; } }; class SofaBed : public Sofa, public Bed { protected: string shape; public: SofaBed(double l, double w, double h, string c, string m, string s): Furniture(l, w, h), Sofa(l, w, h, c), Bed(l, w, h, m), shape(s) {} void showInfo() { Furniture::showInfo(); cout << "Color: " << color << ", Material: " << material << ", Shape: " << shape << endl; } }; int main() { SofaBed sb(2.0, 1.5, 1.0, "Red", "Wood", "L-shape"); sb.showInfo(); return 0; } ``` 在上面的代码中,家具 `Furniture` 包含了长、宽、高三个数据成员,还定义了一个虚函数 `showInfo`,用于展示家具的信息。沙发 `Sofa` `Bed` 分别继承自家具,并新增了颜色材质两个数据成员。它们分别重载了基的 `showInfo` 函数,以展示沙发床的信息。 沙发 `SofaBed` 继承沙发,并使用虚基类继承自家具,以避免家具被多次继承沙发新增了一个形状数据成员,并重载了 `showInfo` 函数。 在主函数中,我们创建了一个沙发床对象 `sb`,并调用了它的 `showInfo` 函数。输出结果为: ``` Length: 2, Width: 1.5, Height: 1 Color: Red, Material: Wood, Shape: L-shape ``` 可以看到,我们的设计合理,并且沙发床对象的信息行为都符合预期。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值