C++ 抽象类实现交通工具:飞机和火车
#include
// 抽象类 Vehicle class Vehicle{ public: virtual float travelTime(float) = 0; // 纯虚函数,计算旅程时间 virtual void setSpeed(float) = 0; // 纯虚函数,设置交通工具速度 };
// Plane 类 class Plane:public Vehicle{ private: float speed; // 飞行速度 public: Plane(float s = 1000):speed(s){} float travelTime(float distance){ return distance/speed; } void setSpeed(float s){ speed = s; } float getSpeed(){ return speed; } };
// Train 类 class Train:public Vehicle{ private: float speed; // 行驶速度 public: Train(float s = 100):speed(s){} float travelTime(float distance){ return distance/speed; } void setSpeed(float s){ speed = s; } float getSpeed(){ return speed; } };
// 主函数 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; }
原文地址: https://www.cveoy.top/t/topic/os6T 著作权归作者所有。请勿转载和采集!