【id:180】【20分】D. 汽车收费(虚函数和多态)

【id:180】【20分】D. 汽车收费(虚函数和多态)_第1张图片

题目描述

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


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给出载客数)。

输出

车的编号、应缴费用


4
1 002 20 5
3 009 30
2 003 50
1 010 17 6


002 170
009 900
003 250
010 148

#include
using namespace std;

class vehicle
{
protected:
	string no;
public:
	vehicle(string n) :no(n) {}
	void virtual display() = 0;//虚函数
};

class car :public vehicle
{
	int num, weight;
public:
	car(string n, int nu, int w) :vehicle(n), num(nu), weight(w) {}//初始化
	void display()
	{
		int sum = num * 8 + weight * 2;
		cout << no << " " << sum << endl;
	}
};

class truck :public vehicle
{
	int weight;
public:
	truck(string n, int w) :vehicle(n), weight(w) {}
	void display()
	{
		int sum = weight * 5;
		cout << no << " " << sum << endl;
	}
};

class bus :public vehicle
{
	int num;
public:
	bus(string n, int nu) :vehicle(n), num(nu) {}
	void display()
	{
		int sum = num * 3;
		cout << no << " " << sum << endl;
	}
};

int main()
{
	int t, type;
	string no;
	int weight, num;

	cin >> t;
	while (t--)
	{
		vehicle* pv;//指针

		cin >> type;
		if (type == 1)
		{
			cin >> no >> num >> weight;
			car c(no, num, weight);
			pv = &c;
			pv->display();//指针指向虚函数 把虚函数覆盖/刷新了
		}
		else if (type == 2)
		{
			cin >> no >> weight;
			truck t(no, weight);
			pv = &t;
			pv->display();
		}
		else if (type == 3)
		{
			cin >> no >> num;
			bus b(no, num);
			pv = &b;
			pv->display();
		}
	}
	return 0;
}

 

你可能感兴趣的:(oj,c++,c++,算法)