一个茶吧提供三类饮料:茶、咖啡和牛奶。其中本地茶要另加50%的服务费,其它茶要加20%的服务费;现磨咖啡要加100%的服务费,其它咖啡加20%的服务费;牛奶不加服务费,服务费精确到小数点一位。
给出下面的基类框架:
Class Drink
{
protected:
int NO; //编号
int amount; //数量
float price; //单价
public:
virtual void display()=0;//输出费用
}
以Drink为基类,构建出Tea, Coffee和Milk三个类。
生成上述类,并编写主函数,要求主函数中有一个基类Drink指针数组,数组元素不超过10个。
Drink *pd[10];
主函数根据输入的信息,相应建立Tea, Coffee或Milk类对象,并给出收费。
输入格式:每个测试用例占一行,每行给出饮料的基本信息,第一个为饮料的类型,茶为1,咖啡为2,牛奶为3。接下来是申请的编号(100-999),然后是数量和单价。对于茶叶来说,接下来输入一个地区代码,其中1代表本地。对于咖啡来说,接下来要输入一个加工代码,其中1代表现磨。最后一行为0。
要求输出编号和收费(小数点后保留1位小数)。
提示:应用虚函数实现多态
输入样例:
1 106 3 33 1
1 103 2 20 2
3 109 1 15
2 107 2 15.8 1
2 232 3 21 29
0
输出样例:
106 148.5
103 48.0
109 15.0
107 63.2
232 75.6
#include<iostream>
#include <iomanip>
using namespace std;
class Drink
{
protected:int NO; //编号int amount; //数量float price; //单价public:
Drink(int NO,int amount,float price){this->NO=NO;this->amount=amount;this->price=price;
}
virtual void display()=0;//输出费用};
class Tea:public Drink{protected:int arr;//地区码 public:Tea(int NO,int amount,float price,int arr):Drink(NO,amount,price){this->arr=arr;}void display(){float add;//总价 if(arr==1){add= amount*price*1.5;//printf("%d %.1f")cout<< NO<<" " <<fixed<<setprecision(1)<<add<<endl; }else{add=amount*price*1.2;cout<< NO<<" " <<fixed<<setprecision(1)<<add<<endl;}}
};
class Coffee:public Drink{protected:int xm;//现磨public:Coffee(int NO,int amount,float price,int xm):Drink(NO,amount,price){this->xm=xm;} void display(){float add;//总价 if(xm==1){add= amount*price*2;cout<< NO<<" " <<fixed<<setprecision(1)<<add<<endl; }else{add=amount*price*1.2;cout<< NO<<" " <<fixed<<setprecision(1)<<add<<endl;}}
};
class Milk:public Drink{public:Milk(int NO,int amount,float price):Drink(NO,amount,price){} void display(){float add;add= amount*price;cout<< NO<<" " <<fixed<<setprecision(1)<<add<<endl; }
};
int main()
{
Drink *pd[10];
int NO; //编号int amount; //数量
int arr,xm;
float price; //单价
int i,ty;
int count=0;cin>>ty;while (ty != 0) {//if(ty==0) break;//endl;switch(ty){case 1:cin>>NO>>amount>>price>>arr;pd[count]=new Tea(NO,amount,price,arr); pd[count]->display();count++;break;case 2:cin>>NO>>amount>>price>>xm;pd[count]=new Coffee(NO,amount,price,xm); pd[count]->display();count++;break;case 3:cin>>NO>>amount>>price;pd[count]=new Milk(NO,amount,price);pd[count]->display();count++;break;}cin>>ty; }return 0;
}