码迷,mamicode.com
首页 > 编程语言 > 详细

【C++ Pimer 第七章】类

时间:2018-07-19 23:27:27      阅读:303      评论:0      收藏:0      [点我收藏+]

标签:disco   string   bool   编号   isp   mes   size   ==   mic   

 

Sales_data类

 1 #ifndef SALES_DATA_H
 2 #define SALES_DATA_H
 3 #include<iostream>
 4 #include<string>
 5 using namespace std;
 6 
 7 class Sales_data
 8 {
 9     friend istream& operator >> (istream &in, Sales_data&);
10     friend ostream& operator << (ostream &os, Sales_data&);
11     friend bool operator == (const Sales_data&, const Sales_data&);
12 public:
13     Sales_data() = default;
14     Sales_data(const string &book): bookNo(book) {}
15     Sales_data(const string  &book, const unsigned num, const double sellp, const double salep, const double disp):
16         bookNo(book), units_sold(num), sellingprice(sellp), discount(disp) {}
17     Sales_data(istream &is) { is >> bookNo }
18 public:
19     Sales_data& operator+=(const Sales_data&);
20     string isbn() const { return bookNo; }
21 private:
22     string bookNo;         //书籍编号
23     double units_sold = 0;  //销售量
24     double sellingprice = 0.0; //原始价格
25     double saleprice = 0.0;   //实售价格
26     double discount = 0.0; //折扣
27 };
28 
29 bool operator== (const Sales_data &lhs, const Sales_data &rhs)
30 {
31     return lhs.isbn() == rhs.isbn() &&
32         lhs.units_sold == rhs.units_sold &&
33         lhs.sellingprice == rhs.sellingprice &&
34         lhs.saleprice == rhs.saleprice;
35 }
36 
37 Sales_data& Sales_data::operator += (const Sales_data &rhs)
38 {
39     units_sold += rhs.units_sold;
40     saleprice = (rhs.saleprice * rhs.units_sold + saleprice * units_sold) / (rhs.units_sold + units_sold);
41     if (sellingprice != 0)
42         discount = saleprice / sellingprice;
43     return *this;
44 }
45 
46 Sales_data operator+ (const Sales_data &lhs, const Sales_data& rhs)
47 {
48     Sales_data ret(lhs);
49     ret += rhs;
50     return ret;
51 }
52 
53 istream& operator >> (istream &in, Sales_data& s)
54 {
55     in >> s.bookNo >> s.units_sold >> s.sellingprice >> s.saleprice;
56     if (in && s.sellingprice != 0)
57         s.discount = s.saleprice / s.sellingprice;
58     else
59         s = Sales_data();
60     return in;
61 }
62 
63 ostream& operator << (ostream &os, const Sales_data &s)
64 {
65     os << s.isbn() << " " << s.units_sold << " "
66         << s.sellingprice << " " << s.saleprice << " " << s.discount;
67     return os;
68 }
69 #endif

 

【C++ Pimer 第七章】类

标签:disco   string   bool   编号   isp   mes   size   ==   mic   

原文地址:https://www.cnblogs.com/sunbines/p/9338952.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!