车的继承(虚基类)

定义一个车(vehicle)基类,具有Speed、Weight等成员变量,Run、Stop等成员函数,由此派生出自行车(bicycle)类,汽车(motorcar)类。自行车(bicycle)类有高度(Height)等属性,汽车(motorcycle)类有座位数(SeatNum)等属性。从bicycle和motorcycle派生出摩托车(Motorcar)类。完成这些类,使得测试代码可以运行并得到正确的输出结果。

函数接口定义:
class Motorcar:public Bicycle,public Motorcycle
Motorcar 必须按照这种方式继承。

裁判测试程序样例:

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

int main(){
    Motorcar  moto(30,50,120,5);
    cout<<"speed "<<moto.speed<<endl;
    cout<<"weight "<<moto.weight<<endl;
    cout<<"height "<<moto.height<<endl;
    cout<<"seatNum "<<moto.seatNum<<endl;
}

输入样例:

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

speed 30
weight 50
height 120
seatNum 5

 

#include <iostream>
using namespace std;

// 车基类
class vehicle {
public:
    int speed;   // 速度
    int weight;  // 重量
    // 构造函数
    vehicle(int s, int w) : speed(s), weight(w) {}

    // 成员函数
    void Run() {
        cout << "Vehicle is running." << endl;
    }
    void Stop() {
        cout << "Vehicle stopped." << endl;
    }
};

// 自行车类,继承自车基类
class Bicycle : virtual public vehicle {
public:
    int height;  // 高度
    // 构造函数
    Bicycle(int s, int w, int h) : vehicle(s, w), height(h) {}
};

// 汽车类,继承自车基类
class Motorcycle : virtual public vehicle {
public:
    int seatNum;  // 座位数
    // 构造函数
    Motorcycle(int s, int w, int seat) : vehicle(s, w), seatNum(seat) {}
};

// 摩托车类,继承自自行车类和汽车类
class Motorcar : public Bicycle, public Motorcycle {
public:
    // 构造函数
    Motorcar(int s, int w, int h, int seat) : vehicle(s, w), Bicycle(s, w, h), Motorcycle(s, w, seat) {}
};

#include<iostream>
using namespace std;

// 车辆基类
class vehicle
{
public:
	int speed;  // 车辆速度
	int weight; // 车辆重量
};

// 自行车类,通过虚拟继承自车辆类
class Bicycle : virtual public vehicle
{
public:
	int height; // 自行车高度
};

// 摩托车类,通过虚拟继承自车辆类
class Motorcycle : virtual public vehicle
{
public:
	int seatNum; // 摩托车座位数
};

// 汽车类,同时继承自自行车和摩托车
class Motorcar : public Bicycle, public Motorcycle
{
public:
	// 构造函数,接受车辆的速度、重量、高度和座位数作为参数
	Motorcar(int m, int w, int h, int s){
		// 将速度和重量分别赋值给车辆基类的成员
		speed = m;
		weight = w;
		// 将高度赋值给自行车的成员
		height = h;
		// 将座位数赋值给摩托车的成员
		seatNum = s;
	}

};

 

 

  • 10
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值