一个茶吧提供三类饮料:茶、咖啡和牛奶。其中本地茶要另加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 <cstdio>
using namespace std;
class Drink {
protected:
int NO;
int amount;
float price;
public:
virtual void display() = 0;
};
class Tea: public Drink {
int code;
public:
Tea(int N, int amou, float p, int c) {
NO = N;
amount = amou;
price = p;
code = c;
}
virtual void display() {
float totalPrice;
if (code == 1) {
totalPrice = price * 1.5 * amount;
} else
totalPrice = price * 1.2 * amount;
cout << NO << ' ' ;
printf("%.1f\n", totalPrice);
}
};
class Coffee: public Drink {
int code;
public:
Coffee(int N, int amou, float p, int c) {
NO = N;
amount = amou;
price = p;
code = c;
}
virtual void display() {
float totalPrice;
if (code == 1) {
totalPrice = price * 2 * amount;
} else
totalPrice = price * 1.2 * amount;
cout << NO << ' ' ;
printf("%.1f\n", totalPrice);
}
};
class Milk: public Drink {
public:
Milk(int N, int amou, float p) {
NO = N;
amount = amou;
price = p;
}
virtual void display() {
float totalPrice = price * amount;
cout << NO << ' ' ;
printf("%.1f\n", totalPrice);
}
};
int main() {
int n, NO, amount, code;
float price;
int count = 0, i;
cin >> n;
Drink *pd[10];
while (n) {
if (n == 3)
cin >> NO >> amount >> price;
else
cin >> NO >> amount >> price >> code;
switch (n) {
case 1:
pd[count++] = new Tea(NO, amount, price, code);
break;
case 2:
pd[count++] = new Coffee(NO, amount, price, code);
break;
case 3:
pd[count++] = new Milk(NO, amount, price);
break;
default:
break;
}
cin >> n;
}
for (i = 0; i < count; i++) {
pd[i]->display();
}
delete *pd;
return 0;
}