虚函数--交通工具(C++)

【问题描述】

定义一个交通工具vehicle,将他作为基类派生校车类car,卡车类truck和轮船类boat,定义类并定义虚函数来显示各类信息

#include  <iostream>

using namespace std;

class vehicle {
protected:
    double speed;        //速度,公里/小时
    int wheels;          //轮子数
    double weight;  //重量
public:
    vehicle(double speed = 80, int wheels = 4, double weight = 1000);

    virtual void show(void) = 0;
};

vehicle::vehicle(double speed, int wheels, double weight) {
    this->speed = speed;
    this->wheels = wheels;
    this->weight = weight;
}


class car : public vehicle {
    int passenger_load;
public:
    car(double speed = 80, int wheels = 4, double weight = 1000, int passenger_load = 4);
    virtual void show(void);
};

void car::show(void) {
    cout << "Car  message\n";
    cout << speed << " " << wheels << " " << weight << " " << passenger_load << endl;
}

car::car(double speed, int wheels, double weight, int passenger_load) {
    this->speed = speed;
    this->wheels = wheels;
    this->weight = weight;
    this->passenger_load = passenger_load;
}


class truck : public vehicle {
    double rated_load;      //额定载重
public:
    truck(double speed = 80, int wheels = 4, double weight = 2500, double rated_load = 3000);

    virtual void show(void);
};

truck::truck(double speed, int wheels, double weight, double rated_load) {
    this->speed = speed;
    this->wheels = wheels;
    this->weight = weight;
    this->rated_load = rated_load;
}

void truck::show(void) {
    cout << "truck message\n";
    cout << speed << " " << wheels << " " << weight << " " << rated_load << endl;
}


class boat : public vehicle {
    char kind;              //轮船类别,如客轮为'k'
public:
    boat(double speed = 30, int wheels = 0, double weight = 12000, char kind = 'k');

    virtual void show(void);
};

boat::boat(double speed, int wheels, double weight, char kind) {
    this->speed = speed;
    this->wheels = wheels;
    this->weight = weight;
    this->kind = kind;
}

void boat::show(void) {
    cout << "boat message\n";
    cout << speed << " " << wheels << " " << weight << " " << kind << endl;
}


int main() {
    vehicle *unicycle;
    car *BMW;
    unicycle = new car;
    unicycle->show();
    BMW = (car *) unicycle;
    BMW->show();
    delete unicycle;
    unicycle = new truck;
    unicycle->show();
    delete unicycle;
    unicycle = new boat;
    unicycle->show();
    delete unicycle;
    return 0;
}  

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

*OASIS*

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值