D. 汽车收费(虚函数和多态)

题目描述

现在要开发一个系统,实现对多种汽车的收费工作。 汽车基类框架如下所示:

class Vehicle
{ 
protected:
     string no; //编号
public:
    virtual void display()=0; //应收费用
}

以Vehicle为基类,构建出Car、Truck和Bus三个类。

Car的收费公式为: 载客数8+重量2

Truck的收费公式为:重量*5

Bus的收费公式为: 载客数*30

生成上述类并编写主函数,要求主函数中有一个基类指针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 900
003 250
010 148

AC代码

#include<iostream>
#include<iomanip>
#include<cstring>
#include<cmath>
using namespace std;
class Vehicle {
protected:
	string no;//编号
public:
	Vehicle(string no):no(no){}
	virtual void display() = 0;//应收费用
};
class Car :public Vehicle {
	int n;
	int weight;
public:
	Car(string no,int n,int weight):Vehicle(no),n(n),weight(weight){}
	virtual void display() {
		cout << no << " " << n * 8 + weight * 2 << endl;
	}
};
class Truck :public Vehicle {
	int weight;
public:
	Truck(string no,  int weight) :Vehicle(no),  weight(weight) {}
	virtual void display() {
		cout << no << " " <<weight * 5 << endl;
	}
};
class Bus :public Vehicle {
	int n;
public:
	Bus(string no, int n) :Vehicle(no), n(n) {}
	virtual void display() {
		cout << no << " " << n * 30 << endl;
	}
};
void Func(Vehicle& p) {
	p.display();
}
int main()
{	
	int t,n,weight,type;
	string no;
	cin >> t;
	Vehicle *p[10];
	//Vehicle* p = new Vehicle[t];
	//不允许使用抽象类类型的对象 抽象类-带有纯虚函数的类
	for(int i=0;i<t;i++) {
		cin >> type;
		if (type == 1) {
			cin >> no>> n >> weight;
			Car A(no, n, weight);
			p[i] = &A;
			Func(*p[i]);
		}
		else if (type == 2) {
			cin >> no >> weight;
			Truck B(no, weight);
			p[i] = &B;
			Func(*p[i]);
		}
		else if (type == 3) {
			cin >> no>>n;
			Bus C(no, n);
			p[i] = &C;
			Func(*p[i]);
		}
	}
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值