# 4004:账单：虚函数应用

Problem Description

int main()
{
sale *ps[20];
int n=0;  //购买商品种数
string name;  //商品名称
double price;  //单价
double count;  //销售量
double discount; //折扣率

int flag;
while(cin>>flag)
{
if(flag==0)   //不打折商品
{
cin>>name>>price>>count;
//补充完整
}
else if(flag==1)    //打折商品
{
cin>>name>>price>>count>>discount;
//补充完整
}

}

double total=0;
for(int i=0;i<n;i++)
{
ps[i]->show();   //显示第i个商品信息
total+=ps[i]->bill();  //累计总金额
delete ps[i];
}
cout<<"Total:"<<total<<endl;

return 0;
} 

Input

Output

Sample Input

0 apple 5.2 3
1 rice 3.5 2 0.85
0 pear 3 2
0 grape 8 1.5

Sample Output

apple   5.2 3   15.6
rice    3.5 2   0.85    5.95
pear    3   2   6
grape   8   1.5 12
Total:39.55

## 答案

#include <iostream>
#include <string>
using namespace std;
class sale
{
protected:
string name;
double price,sales;
public:
sale() {}
sale(string name,double price,double sales):
name(name),sales(sales),price(price) {}
virtual double bill()
{
return sales*price;
}
virtual void show()
{
cout<<name<<"\t"<<price<<"\t"<<sales<<"\t"
<<bill()<<endl;
}
};
class discountSale:public sale
{
private:
double count;
public:
discountSale(string name,double price,double sales,double count):
sale(name,price,sales),count(count) {}
double bill()
{
return sales*price*count;
}
void show()
{
cout<<name<<"\t"<<price<<"\t"<<sales<<"\t"
<<count<<"\t"<<bill()<<endl;
}
};

int main()
{
sale *ps[20];
int n=0;  //购买商品种数
string name;  //商品名称
double price;  //单价
double count;  //销售量
double discount; //折扣率

int flag;
while(cin>>flag)
{
if(flag==0)   //不打折商品
{
cin>>name>>price>>count;
ps[n++]=new sale(name,price,count);
}
else if(flag==1)    //打折商品
{
cin>>name>>price>>count>>discount;
ps[n++]=new discountSale(name,price,count,discount);
}
}

double total=0;
for(int i=0; i<n; i++)
{
ps[i]->show();   //显示第i个商品信息
total+=ps[i]->bill();  //累计总金额
delete ps[i];
}
cout<<"Total:"<<total<<endl;

return 0;
}

11-26
07-10 1万+
07-10 1902
07-10 2885
05-23 8060
07-11 5857
04-22 1万+
07-06 661
12-02 5702
11-22
01-29 5962
12-23
06-06 5万+
©️2020 CSDN 皮肤主题: 精致技术 设计师:CSDN官方博客