首页 > 代码库 > C++primer 7.1.3节练习

C++primer 7.1.3节练习

练习7.6

 1 #include <iostream>
 2 #include <string>
 3 #include "factmain.h"
 4 using namespace std;
 5 
 6 struct Sales_data {
 7     string  isbn() const { return bookNo; }
 8     Sales_data &combine(const Sales_data&);
 9     string bookNo;
10     unsigned units_sold;
11     double price = 0.0;
12     double revenue = 0.0;
13 };
14 
15 Sales_data add(const Sales_data &lhs, const Sales_data &rhs);
16 ostream &print(ostream &os, const Sales_data &item);
17 istream &read(istream &is, Sales_data &item);
18 
19 
20 int main()
21 {
22     Sales_data item1, item2;
23     double totalRevenue = 0;
24     double totalSold = 0;
25     int counter = 1;
26     if (read(cin, item1))
27     {
28         item1.revenue = item1.price * item1.units_sold;
29         while (read(cin,item2)) {
30             item2.revenue = item2.price * item2.units_sold;
31             if (item1.bookNo == item2.bookNo) {
32                 item1.combine(item2);
33                 ++counter;
34             }
35             else {
36                 print(cout, item1) << endl;
37                 item1.bookNo = item2.bookNo;
38                 item1.units_sold = item2.units_sold;
39                 item1.revenue = item2.revenue;
40                 counter = 1;
41             }
42         }
43         print(cout, item2) << endl;
44     }
45     return 0;
46 }
47 
48 Sales_data add(const Sales_data & lhs, const Sales_data & rhs) //非成员函数add
49 {
50     Sales_data sum = lhs;
51     sum.combine(rhs);
52     return sum;
53     // TODO: 在此处插入 return 语句
54 }
55 
56 istream & read(istream & is, Sales_data & item)
57 {
58     is >> item.bookNo >> item.units_sold >> item.price;
59     item.revenue = item.units_sold * item.price;
60     return is;
61     // TODO: 在此处插入 return 语句
62 }
63 
64 ostream & print(ostream & os, const Sales_data & item)
65 {
66     os << item.bookNo << " " << item.units_sold << " " << item.price << " " << item.revenue;
67     return os;
68     // TODO: 在此处插入 return 语句
69 }
70 
71 Sales_data & Sales_data::combine(const Sales_data &rhs)
72 {
73     units_sold += rhs.units_sold;
74     revenue += rhs.revenue;
75     return *this;
76 }

练习7.7

见上

练习7.8

read里面涉及到revenue的计算,item.revenue被更新,因此定义为普通的引用;而print只是输出对象的值,故可以声明为常量引用;

练习7.9

见本章最后的程序吧。

练习7.10

判断data1和data2的输入是否正确(非空或者输入错误),先输入data1,在输入data2;

C++primer 7.1.3节练习