标签:unsigned log code prime else read c++ prime 成员 inline
练习
7.6 & 7.7
#include <iostream> #include <string> using namespace std; // Sales_data.h struct Sales_data { // public部分,对象看起来是怎么样的。 std::string isbn() const { return bookNo; } // inline function Sales_data& combine(const Sales_data&); double avg_price() const; // private部分,数据成员。 std::string bookNo; unsigned units_sold = 0; double revenue = 0.0; }; // Sales_data的非成员接口函数 Sales_data add(const Sales_data&, const Sales_data&); std::ostream &print(std::ostream&, const Sales_data&); std::istream &read(std::iostream&, Sales_data&); // Sales_data.cpp Sales_data& Sales_data::combine(const Sales_data &rhs) { units_sold += rhs.units_sold; revenue += rhs.revenue; return *this; } istream &read(istream &is, Sales_data &item) { double price = 0; is >> item.bookNo >> item.units_sold >> price; item.revenue = price * item.units_sold; return is; } ostream &print(ostream &os, const Sales_data &item) { os << item.isbn() << " " << item.units_sold << " " << item.revenue << " " << item.avg_price(); return os; } double Sales_data::avg_price() const { if (units_sold) return revenue/units_sold; else return 0; } Sales_data add(const Sales_data &lhs, const Sales_data &rhs) { Sales_data sum = lhs; sum.combine(rhs); return sum; } // main.cpp 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 { cerr << "No data?!" << endl; } return 0; }
7.8
read操作会改变对象的数据成员,而print操作仅仅是“访问”而不改变对象的数据成员。
标签:unsigned log code prime else read c++ prime 成员 inline
原文地址:http://www.cnblogs.com/xkxf/p/6668881.html