This repository was archived by the owner on Apr 21, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathex14_45.h
98 lines (78 loc) · 2.45 KB
/
ex14_45.h
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
#ifndef EX_14_2_H
#define EX_14_2_H
#include "headers.h"
struct Sales_data;
class Sales_data {
friend istream& operator>>(istream& is, Sales_data& d);
friend ostream& operator<<(ostream& os, const Sales_data& d);
friend Sales_data operator+(const Sales_data& lhs, const Sales_data& rhs);
friend bool operator==(const Sales_data& lhs, const Sales_data& rhs);
friend bool operator!=(const Sales_data& lhs, const Sales_data& rhs);
public:
Sales_data() = default;
Sales_data(const string& s, unsigned n, double p) : bookNo(s), units_sold(n), revenue(n * p) {}
Sales_data(const string& s) : bookNo(s) {}
Sales_data(istream& is);
const string isbn() const { return bookNo; }
Sales_data& combine(const Sales_data&);
double avg_price() const;
Sales_data& operator+=(const Sales_data& other);
Sales_data& operator=(const string& new_bookNo);
// Misleading conversion operator
operator string() const { return bookNo; };
operator double() const { return revenue / units_sold; };
private:
string bookNo;
unsigned units_sold = 0;
double revenue = 0.0;
};
Sales_data::Sales_data(istream& is) {
is >> *this;
}
Sales_data& Sales_data::combine(const Sales_data& that) {
units_sold += that.units_sold;
revenue += that.revenue;
return *this;
}
double Sales_data::avg_price() const {
if (units_sold) {
return revenue / units_sold;
}
return 0.0;
}
Sales_data& Sales_data::operator+=(const Sales_data& other) {
if (bookNo != other.isbn()) {
cout << "Not transaction of the same kind of book, cannot add!" << endl;
} else {
units_sold += other.units_sold;
revenue += other.revenue;
}
return *this;
}
Sales_data operator+(const Sales_data& lhs, const Sales_data& rhs) {
Sales_data sum = lhs;
sum += rhs;
return sum;
}
Sales_data& Sales_data::operator=(const string& new_bookNo) {
bookNo = new_bookNo;
return *this;
// Could be a more sensible version.
// *this = Sales_data(new_bookNo);
// return *this;
}
istream& operator>>(istream& is, Sales_data& data) {
double price;
is >> data.bookNo >> data.units_sold >> price;
if (is) {
data.revenue = price * data.units_sold;
} else {
data = Sales_data();
}
return is;
}
ostream& operator<<(ostream& os, const Sales_data& data) {
os << data.isbn() << " " << data.units_sold << " " << data.avg_price() << endl;
return os;
}
#endif