现在要开发一个系统,管理对多种汽车的收费工作。 给出下面的一个基类框架
class Vehicle
{ protected:
string NO;//编号
public:
virtual void display()=0;//输出应收费用
}
以Vehicle为基类,构建出Car、Truck和Bus三个类。
Car的收费公式为: 载客数8+重量2
Truck的收费公式为:重量*5
Bus的收费公式为: 载客数*3
生成上述类并编写主函数,要求主函数中有一个基类Vehicle指针数组,数组元素不超过10个。
Vehicle *pv[10];
主函数根据输入的信息,相应建立Car,Truck或Bus类对象,对于Car给出载客数和重量,Truck给出重量,Bus给出载客数。假设载客数和重量均为整数
输入格式:每个测试用例占一行,每行给出汽车的基本信息,每一个为当前汽车的类型1为car,2为Truck,3为Bus。接下来为它的编号,接下来Car是载客数和重量,Truck给出重量,Bus给出载客数。最后一行为0,表示输入的结束。 要求输出各车的编号和收费。
提示:应用虚函数实现多态
输入样例
1 002 20 5
3 009 30
2 003 50
1 010 17 6
0
输出样例
002 170
009 90
003 250
010 148
实现代码如下:
#include<iostream> #include <string> using namespace std; class Vehicle { protected: string NO;//编号 public: Vehicle(string n){ NO = n; } virtual int fee()=0;//计算应收费用 }; class Car:public Vehicle{ int guest; int weight; public: Car(string no,int g,int w):Vehicle(no){ guest=g; weight=w; } int fee(){ return guest*8+weight*2; } }; class Truck:public Vehicle{ int weight; public: Truck(string no,int w):Vehicle(no){ weight=w; } int fee(){ return weight*5; } }; class Bus:public Vehicle{ int guest; public: Bus(string no,int g):Vehicle(no){ guest=g; } int fee(){ return guest*3; } }; int main() { Car c("",0,0); Truck t("",0); Bus b("",0); int i, ty, weight, guest; string no; while(1){ cin>>ty; if(ty==0) break; cin>>no; switch(ty){ case 1: cin>>guest>>weight; c=Car(no, guest, weight); cout<<no<<' '<<c.fee()<<endl; break; case 2: cin>>weight; t=Truck(no, weight); cout<<no<<' '<<t.fee()<<endl; break; case 3: cin>>guest; b=Bus(no, guest); cout<<no<<' '<<b.fee()<<endl; break; } } return 0; }