forked from pezy/CppPrimer
-
Notifications
You must be signed in to change notification settings - Fork 0
/
ex7_21.cpp
114 lines (97 loc) · 2.78 KB
/
ex7_21.cpp
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
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
//! @Alan
//!
//! Exercise 7.21:
//! Update your Sales_data class to hide its implementation.
//! The programs you’ve written to use Sales_data operations should still
//! continue to work. Recompile those programs with your new class definition
//! to verify that they still work.
//!
#include <iostream>
#include <string>
class wy_Sales_data
{
//!
//! \brief Exercise 7.21
//! @note friends
//!
friend wy_Sales_data add (const wy_Sales_data &lhs, const wy_Sales_data &rhs);
friend std::istream &read (std::istream &is, wy_Sales_data &sd);
friend std::ostream &print (std::ostream &os, const wy_Sales_data &sd);
private:
std::string bookNo;
unsigned units_sold = 0;
double revenue = 0.0;
public:
//! constructors:
wy_Sales_data() = default; //default
//wy_Sales_data() : units_sold(0) , revenue(0){}
wy_Sales_data(const std::string &str) : bookNo(str) {} //with bookNo
wy_Sales_data(const std::string &str, unsigned uni, double prc) :
bookNo(str), units_sold(uni), revenue(uni * prc){} //with all
wy_Sales_data(std::istream &is)
{
double price;
is >> this->bookNo >> this->units_sold >> price;
this->revenue = price * this->units_sold;
}
//! member functions:
std::string isbn(void) const {return this->bookNo;}
wy_Sales_data &combine (const wy_Sales_data &sd);
};
//! friend:
wy_Sales_data add (const wy_Sales_data &lhs, const wy_Sales_data &rhs);
std::istream &read (std::istream &is, wy_Sales_data &sd);
std::ostream &print (std::ostream &os, const wy_Sales_data &sd);
int main()
{
std::cout << "Please enter the first book:\n";
wy_Sales_data total(std::cin);
while(true)
{
std::cout << "Please enter the next book:\n";
wy_Sales_data trans(std::cin);
if(total.isbn() == trans.isbn())
{
total = add(total, trans);
}
else
{
print(std::cout,total);
std::cout<<"\n";
total = trans;
}
}
return 0;
}
/*
wy_Sales_data::wy_Sales_data( std::istream &is)
{
read(is,*this);
}
*/
wy_Sales_data &wy_Sales_data::combine(const wy_Sales_data &sd)
{
this->revenue += sd.revenue;
this->units_sold += sd.units_sold;
return *this;
}
std::istream &read(std::istream &is, wy_Sales_data &sd)
{
double price;
is >> sd.bookNo >> sd.units_sold >> price;
sd.revenue = price * sd.units_sold;
return is;
}
std::ostream &print(std::ostream &os, const wy_Sales_data &sd)
{
os << sd.isbn() << " "
<< sd.revenue << " "
<< sd.units_sold;
return os;
}
wy_Sales_data add(const wy_Sales_data &lhs, const wy_Sales_data &rhs)
{
wy_Sales_data sum =lhs;
sum.combine(rhs);
return sum;
}