C++primer 7.1.2节练习

练习7,2

 1 #include <iostream>
 2 #include <string>
 3 using namespace std;
 4 
 5 struct Sales_data {
 6     string bookNo;
 7     unsigned units_sold;
 8     double price = 0.0;
 9     double revenue = 0.0;
10     Sales_data &combine(const Sales_data&);
11     string  isbn() const {return bookNo;}
12 };
13 
14 Sales_data & Sales_data::combine(const Sales_data &rhs)
15 {
16         units_sold += rhs.units_sold;
17         revenue += rhs.revenue;
18         return *this;
19 }
20 
21 int main()
22 {
23     Sales_data item1, item2;
24     double totalRevenue = 0;
25     double totalSold = 0;
26     int counter = 1;
27     if (cin >> item1.bookNo >> item1.units_sold >> item1.price)
28     {
29         item1.revenue = item1.price * item1.units_sold;
30         while (cin >> item2.bookNo >> item2.units_sold >> item2.price) {
31             item2.revenue = item2.price * item2.units_sold;
32             if (item1.bookNo == item2.bookNo) {
33                 item1.combine(item2);
34                 ++counter;
35             }
36             else {
37                 cout << item1.isbn() << " " << item1.units_sold << " " << item1.revenue << " Times:" << counter << endl;
38                 item1.bookNo = item2.bookNo;
39                 item1.units_sold = item2.units_sold;
40                 item1.revenue = item2.revenue;
41                 counter = 1;
42             }
43         }
44         cout << item1.bookNo << " " << item1.units_sold << " " << item1.revenue << " Times:" << counter << std::endl;
45     }
46     return 0;
47 }

练习7.3

见上面代码

练习7.4

1 struct person {
2     string person_name;//人员姓名
3     string person_add;//人员居住地址
4 };

练习7.5

1         string backName() const { return person_name; }
2     string backAddr() const { return person_addr; }    

应该是const,在这两个函数体内不会改变this所指的对象,所以把this设置为指向常量的指针有助于提高函数的灵活性。

posted @ 2017-08-04 19:29  五月份小姐  阅读(242)  评论(0编辑  收藏  举报