C++ Primer(第5版) 练习 7.3
练习 7.3 修改7.1.1节(第229页)的交易处理程序,令其使用这些成员。
环境:Linux Ubuntu(云服务器)
工具:vim
代码块
/*************************************************************************> File Name: ex7.3.cpp> Author: > Mail: > Created Time: Thu 15 Feb 2024 12:26:50 PM CST************************************************************************/#include<iostream>
using namespace std;struct 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_preturn 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;if(read(cin, total)){Sales_data trans;while(read(cin, trans)){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;
}