C++ Primer(第5版) 练习 7.13
练习 7.13 使用istream构造函数重写第229页的程序。
环境:Linux Ubuntu(云服务器)
工具:vim
代码块
/*************************************************************************
> File Name: ex7.13.cpp
> Author:
> Mail:
> Created Time: Thu 15 Feb 2024 12:26:50 PM CST
************************************************************************/
#include<iostream>
using namespace std;
struct Sales_data{
Sales_data() = default;
Sales_data(const string &s): bookNo(s) {}
Sales_data(const string &s, unsigned n, double p):
bookNo(s), units_sold(n), price(p), revenue(p * n) {}
Sales_data(istream &in) { read(in, *this); }
friend ostream &print(ostream&, const Sales_data&);
friend istream &read(istream&, Sales_data&);
string isbn() const;
Sales_data& combine(const Sales_data&);
double avg_price() const;
string bookNo;
unsigned units_sold = 0;
double price = 0.0;
double revenue = 0.0;
};
string Sales_data::isbn() const{
return this->bookNo;
}
Sales_data& Sales_data::combine(const Sales_data &rhs){
units_sold += rhs.units_sold;
revenue += rhs.revenue;
return *this;
}
double Sales_data::avg_price() const{
if(units_sold){
return revenue / units_sold;
}
else{
return 0;
}
}
Sales_data add(const Sales_data &sd1, const Sales_data &sd2){
Sales_data t = sd1;
t.combine(sd2);
return t;
}
ostream &print(ostream &output, const Sales_data &sd){
output<<sd.bookNo<<" "<<sd.units_sold<<" "<<sd.price<<" "<<sd.revenue<<" "<<sd.avg_p
return output;
}
istream &read(istream &input, Sales_data &sd){
input>>sd.bookNo>>sd.units_sold>>sd.price;
sd.revenue = sd.price * sd.units_sold;
return input;
}
int main(){
Sales_data total(cin);
if(!total.isbn().empty()){
while(cin){
Sales_data trans(cin);
if(total.isbn() == trans.isbn()){
total.combine(trans);
}
else{
print(cout, total)<<endl;
total = trans;
}
}
print(cout, total)<<endl;
}
else{
cout<<"No data?!"<<endl;
}
return 0;
}