汽車收費 C++ PTA


7-1 汽車收費(10 分)

現在要開發一個系統,管理對多種汽車的收費工作。 給出下面的一個基類框架

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           // 父類、基類  Vehicle
{  
protected:              // 安全屬性 
    string NO;          // 編號  
public:                  // 公共屬性 
    Vehicle(string n) // 獲取編號 
    {
        NO = n;  
    }  
    virtual int money()=0;//計算應收費用  
};  
  
class Car:Vehicle        // 子類Car,繼承父類Verhicle 
{  
    public:  
        int guest,weight;  
        Car(string no1,int guest1,int weight1):Vehicle(no1)  
        {   
            weight=weight1;  
            guest=guest1;  
        }  
        int money()  
        {     
            return guest*8+weight*2;  //  載客數8+重量2 
        }  
};   

class Truck:Vehicle  // 子類Truck,繼承父類Verhicle  
{  
        public:  
        int weight;  
        Truck(string no1,int weight1):Vehicle(no1)  
        {   
            weight=weight1;  
        }  
        int money()  
        {     
            return weight*5;  // 重量*5
        }  
};  

class Bus:Vehicle    // 子類Bus,繼承父類Verhicle 
{   public:  
        int guest;  
        Bus(string no1,int guest1):Vehicle(no1)  
        {     
            guest=guest1;  
        }  
        int money()  
        {     
            return guest*3;  // 載客數*3
        }  
};  

int main()  
{  
    Car car("",0,0);  // 實例化對象類,初始化Car的 載客數量,重量  
    Truck truck("",0);  
    Bus bus("",0);
      
    int i, repeat, type, weight, guest;  
    string no;  
    while(cin >> type )
       
       {
        if(type == 0)
            break;else switch(type) { case 0: break; // 輸入0退出的功能沒有成功 case 1: cin >> no >> guest >> weight; // 獲取 Car的 載客數量,重量 car = Car(no, guest, weight); cout << no << ' ' << car.money() << endl; // 輸出收費 break; case 2: cin >> no >> weight; // 獲取Truck 的重量 truck = Truck(no, weight); cout << no << ' ' << truck.money() << endl; break; case 3: cin >> no >> guest; // 獲取Bus的載客數 bus = Bus(no, guest); cout << no << ' ' << bus.money() << endl; break; } } return 0; }

注:程序可能不能按要求正確運行,因為我笨啊!


 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM