题目描述
现在要开发一个系统,实现对多种汽车的收费工作。 汽车基类框架如下所示:
class Vehicle
{ protected:
string no;//编号
public:
virtual void display()=0;//应收费用
}
以Vehicle为基类,构建出Car、Truck和Bus三个类。
Car的收费公式为: 载客数*8+重量*2
Truck的收费公式为:重量*5
Bus的收费公式为: 载客数*3
生成上述类并编写主函数,要求主函数中有一个基类指针Vehicle *pv;用来做测试用。
主函数根据输入的信息,相应建立Car,Truck或Bus类对象,对于Car给出载客数和重量,Truck给出重量,Bus给出载客数。假设载客数和重量均为整数。
输入
第一行表示测试次数。从第二行开始,每个测试用例占一行,每行数据意义如下:汽车类型(1为car,2为Truck,3为Bus)、编号、基本信息(Car是载客数和重量,Truck给出重量,Bus给出载客数)。
输出
车的编号、应缴费用
输入样例1
4
1 002 20 5
3 009 30
2 003 50
1 010 17 6
输出样例1
002 170
009 90
003 250
010 148
思路分析
考查类的多态和虚函数的简单应用,通过将基类的成员函数设定为虚函数,在主函数中利用一个基类指针来创建不同的子类对象,使用基类指针可以自动调用相应的子类成员函数。
AC代码
#include"iostream"
#include"string"
using namespace std;
class Vehicle
{
protected:
string no;
public:
Vehicle(string no):no(no){}
virtual void display()= 0;
};
class Car :public Vehicle
{
int constomer, heavy;
public:
Car(string no,int constomer,int heavy):constomer(constomer),heavy(heavy),Vehicle(no) {
}
virtual void display() { cout << no << " " <<8*constomer+2*heavy<< endl; }
};
class Truck :public Vehicle
{
int heavy;
public:
Truck(string no,int heavy) :heavy(heavy), Vehicle(no) {
}
virtual void display() { cout << no << " " << 5* heavy << endl; }
};
class Bus :public Vehicle
{
int constomer;
public:
Bus(string no,int constomer) :constomer(constomer),Vehicle(no) {
}
virtual void display() { cout << no << " " << 3 * constomer<< endl; }
};
int main()
{
int t, heavy,constomer,kind;
cin >> t;
Vehicle * pv;
string no;
while (t--)
{
cin>> kind>> no;
if (kind == 1)
{
cin >> constomer >> heavy;
pv = new Car(no, constomer, heavy);
}
else if (kind == 2)
{
cin >> heavy;
pv = new Truck(no,heavy);
}
else
{
cin >> constomer;
pv = new Bus(no, constomer);
}
pv->display();
}
}