练习
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::istream&, 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操作仅仅是“访问”而不改变对象的数据成员。
7.9
#include <iostream> #include <string> using namespace std; // Person.h struct Person { // public string getName() const { return name; } string getAddress() const { return address; } // private string name; string address; }; istream &read(istream&, Person&); ostream &print(ostream&, const Person&); // Person.cpp istream &read(istream &is, Person &p) { is >> p.name >> p.address; return is; } ostream &print(ostream &os, const Person &p) { os << p.getName() << " " << p.getAddress(); return os; } // main.cpp int main() { Person p; read(cin, p); print(cout, p) << endl; return 0; }
7.10
读入两条数据。