【C++OJ多重继承与虚拟继承】OOP 水陆两用汽车(多重继承+虚拟继承)
题目描述
设计水陆两用汽车类。
定义Vehicle基类,包含成员变量:重量weight;成员函数:构造函数,setWeight,函数display
定义Car类,继承于Vehicle类,包含成员变量:空气排量aird;成员函数:构造函数,setAird,display
定义Boat类,继承于Vehicle类,包含成员变量:排水量tonnage;成员函数:构造函数,setTonnage,display
定义AmphibianCar类,继承于Car类与Boat类,包含成员函数:构造函数,display
构造AmphibianCar类(构造函数中输出相关信息),并输出相关属性值。随后修改各项属性值(set函数中输出相关信息),并输出。
输入
输入重量,空气排量,排水量
输入修改后的重量,空气排量,排水量
输出
构造AmphibianCar类(构造函数中输出相关信息),并输出相关属性值。随后修改各项属性值(set函数中输出相关信息),并输出。
输入样例
4 200 1.35
5 201 1.25
输出样例
载入Vehicle类构造函数
载入Car类构造函数
载入Boat类构造函数
载入AmphibianCar类构造函数
重量:4吨,空气排量:200CC,排水量:1.35吨
重新设置重量
重新设置空气排量
重新设置排水量
重量:5吨,空气排量:201CC,排水量:1.25吨
参考代码
#include <iostream>
using namespace std;
class Vehicle //定义Vehicle基类
{
public: //成员函数:构造函数,setWeight,函数display
Vehicle(int wval) : weight(wval)
{
cout << "载入Vehicle类构造函数" << endl;
}
void setWeight(int wval)
{
weight = wval;
cout << "重新设置重量" << endl;
}
void display()
{
cout << "重量:" << weight << "吨,";
}
protected:
int weight; //包含成员变量:重量weight;
};
//虚拟继承,只产生一个拷贝。(解决多继承时可能发生的对同一基类继承多次而产生的二义性问题)
class Car : virtual public Vehicle //定义Car类,继承于Vehicle类。
{
public: //成员函数:构造函数,setAird,display
Car(int wval, int aval) : Vehicle(wval), aird(aval)
{
cout << "载入Car类构造函数" << endl;
}
void setAird(int aval)
{
aird = aval;
cout << "重新设置空气排量" << endl;
}
void display()
{
cout << "空气排量:" << aird << "CC,";
}
protected:
int aird; //包含成员变量:空气排量aird
};
class Boat : virtual public Vehicle //定义Boat类,继承于Vehicle类 虚拟继承
{
public: //成员函数:构造函数,setTonnage,display
Boat(int wval, float tval) : Vehicle(wval), tonnage(tval)
{
cout << "载入Boat类构造函数" << endl;
}
void setTonnage(float tval)
{
tonnage = tval;
cout << "重新设置排水量" << endl;
}
void display()
{
cout << "排水量:" << tonnage << "吨";
}
protected:
float tonnage; //包含成员变量:排水量tonnage
};
class AmphibianCar : public Car, public Boat //水陆两用汽车类,多重继承
{
public:
AmphibianCar(int wval, int aval, float tval) : Vehicle(wval), Car(wval, aval), Boat(wval, tval) //构造函数
{
cout << "载入AmphibianCar类构造函数" << endl; //构造AmphibianCar类(构造函数中输出相关信息),并输出相关属性值
}
void setAmphibianCar(int wval, int aval, float tval) //修改各项属性值(set函数中输出相关信息)
{
Vehicle::setWeight(wval);
Car::setAird(aval);
Boat::setTonnage(tval);
display();
}
void display()
{
Vehicle::display();
Car::display();
Boat::display();
cout << endl;
}
};
int main()
{
int weight, aird;
float tonnage;
cin >> weight >> aird >> tonnage;
AmphibianCar a(weight, aird, tonnage);
a.display();
cin >> weight >> aird >> tonnage;
a.setAmphibianCar(weight, aird, tonnage);
}