標籤:person com include als space add ++ amp sign
練習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設定為指向常量的指標有助於提高函數的靈活性。
C++primer 7.1.2節練習