C++primer 7.1.2節練習

來源:互聯網
上載者:User

標籤: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節練習

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.