思路:

定义一个抽象类 Vehicle,包含 travelTime 和 setSpeed 两个纯虚函数。然后派生出两个类 Plane 和 Train,分别实现这两个函数,并新增各自的数据成员和函数成员。在主函数中,分别测试两个类的成员函数。

具体实现:

  1. Vehicle 类:

class Vehicle { public: virtual float travelTime(float distance) = 0; virtual void setSpeed(float speed) = 0; };

  1. Plane 类:

class Plane : public Vehicle { private: float speed; public: Plane(float speed = 1000) : speed(speed) {} float travelTime(float distance) { return distance / speed; } void setSpeed(float speed) { this->speed = speed; } float getSpeed() { return speed; } };

  1. Train 类:

class Train : public Vehicle { private: float speed; public: Train(float speed = 100) : speed(speed) {} float travelTime(float distance) { return distance / speed; } void setSpeed(float speed) { this->speed = speed; } float getSpeed() { return speed; } };

  1. 主函数:

int main() { Vehicle *v; Plane p; Train t; int i; float s, d; cout << "飞机的速度:" << p.getSpeed() << endl; cout << "火车的速度:" << t.getSpeed() << endl; cout << "请输入交通工具类型号(1飞机,2火车)、速度以及路程:" << endl; cin >> i >> s >> d; if (i == 1 || i == 2) { if (i == 1) { v = &p; v->setSpeed(s); cout << "飞机的旅程时间:" << v->travelTime(d) << endl; } else { v = &t; v->setSpeed(s); cout << "火车的旅程时间:" << v->travelTime(d) << endl; } } return 0; }

完整代码

定义描述交通工具的抽象类Vehicle并由Vehicle类派生出两种交通工具——飞机类Plane和火车类Train主函数完成相关的测试。Vehicle类结构说明:Vehicle类的成员函数包括:①公有函数成员float travelTimefloat是纯虚函数它的功能是根据旅程距离计算旅程时间。②公有函数成员void setSpeedfloat是纯虚函数它的功能是用于设置交通工具速度。Plane类

原文地址: https://www.cveoy.top/t/topic/f2hn 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录