标签:double revenue include return price
练习7.7: 使用这些新函数重写7.1.2节练习中的交易处理程序
//Sales.data.h #ifndef SALES_DATA_H #define SALES_DATA_H #include <iostream> #include <string> struct Sales_data { std::string isbn() const{return bookNO;} double avg_price() const; Sales_data& combine(const Sales_data&); unsigned units_sold=0; std::string bookNO; double revenue=0.0; double price=0.0; }; double Sales_data::avg_price() const { if(units_sold) return revenue/units_sold; else return 0; } Sales_data& Sales_data::combine(const Sales_data &rhs) { units_sold+=rhs.units_sold; revenue+=rhs.revenue; return *this; } std::istream& read(std::istream &is,Sales_data &item) { is>>item.bookNO>>item.units_sold>>item.price; item.revenue=item.units_sold*item.price; return is; } std::ostream& print(std::ostream &os,const Sales_data &item) { os<<item.isbn()<<" "<<item.units_sold<<" "<<item.revenue<<" "<<item.avg_price(); return os; } Sales_data add(const Sales_data &lhs,const Sales_data &rhs) { Sales_data sum=lhs; sum.combine(rhs); return sum; } #endif // SALES_DATA_H
//main.cpp #include "Sales_data.h" int main(int argc,const char **argv) { Sales_data total; if(read(std::cin,total)) { Sales_data trans; while(read(std::cin,trans)) { if(total.isbn()==trans.isbn()) { total=add(total,trans); } else { print(std::cout,total)<<std::endl; total=trans; } } print(std::cout,total); } else { std::cerr<<"No data?"<<std::endl; } }
本文出自 “奔跑的驴” 博客,请务必保留此出处http://amgodchan.blog.51cto.com/9521586/1568244
标签:double revenue include return price
原文地址:http://amgodchan.blog.51cto.com/9521586/1568244