【id:261】【20分】C. 汽车收费(虚函数和多态)
时间限制
1s
内存限制
128MB
题目描述
现在要开发一个系统,实现对多种汽车的收费工作。 汽车基类框架如下所示:
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
纯虚函数的格式
virtual void display() = 0;
虚函数的格式:只需要在函数前面加virtual,可以有函数体
基类存在纯虚函数时,子类需要对其进行实现,才能进行创建对象
#include "iostream"
#include "vector"
using namespace std;
class Vehicle {
protected:
string no;//编号
public:
explicit Vehicle(const string &no) : no(no) {}
virtual void display() = 0;//应收费用
};
//以Vehicle为基类,构建出Car、Truck和Bus三个类。
// Car 的收费公式为: 载客数*8+重量*2
// Truck 的收费公式为:重量*5
// Bus 的收费公式为: 载客数*3
class Car : virtual public Vehicle {
public:
int weight;
int number;
Car(const string &no, int weight, int number) : Vehicle(no), weight(weight), number(number) {}
virtual void display() {
cout << no << " " << (number * 8 + weight * 2) << endl;
}
};
class Truck : virtual public Vehicle {
public:
int weight;
Truck(const string &no, int weight) : Vehicle(no), weight(weight) {}
virtual void display() {
cout << no << " " << (weight * 5) << endl;
}
};
class Bus : virtual public Vehicle {
public:
int number;
Bus(const string &no, int number) : Vehicle(no), number(number) {}
virtual void display() {
cout << no << " " << (number * 3) << endl;
}
};
int main() {
//第一行表示测试次数。
int times;
cin >> times;
// 从第二行开始,每个测试用例占一行,
int type;
string no;//编号
// 每行数据意义如下:汽车类型(1为car,2为Truck,3为Bus)、编号、基本信息(Car是载客数和重量,Truck给出重量,Bus给出载客数)。
Vehicle *vehicle;
while (times--) {
cin >> type >> no;
switch (type) {
case 1: {
int weight;
int number;
cin >> number >> weight;
vehicle = new Car(no, weight, number);
break;
}
case 2: {
int weight;
cin >> weight;
vehicle = new Truck(no, weight);
break;
}
case 3: {
int number;
cin >> number;
vehicle = new Bus(no, number);
break;
}
}
vehicle->display();
}
}