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设置为指向常量的指针有助于提高函数的灵活性。

转载于:https://www.cnblogs.com/wuyinfenghappy/p/7286801.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值