The contents of “salesItem.h” is shown as follow,
#ifndef SALESITEM_H
#define SALESITEM_H
#include
class salesItm
{
friend std::istream& operator>>(std::istream&, salesItm&);
friend std::ostream& operator *this; //using istream to read variable *this
}
public:
// operations on SalesItm objects
// for member binary operator: left-hand operand bound to implicit this pointer
salesItm& operator+=(const salesItm&);
double avgPrice() const;
bool sameIsbn(const salesItm &rhs) const {return isbn == rhs.isbn;}
salesItm(): unitsSold(0), revenue(0.0){}
private:
std::string isbn;
unsigned short unitsSold;
double revenue;
};
// nonmember binary operator: must declare a parameter for each operand
salesItm operator+(const salesItm&, const salesItm&);
double salesItm::avgPrice() const
{
if(unitsSold)
{
return revenue/unitsSold;
}
else
{
return 0;
}
}
inline
bool
operator==(const salesItm &lhs, const salesItm &rhs)
{
return lhs.unitsSold == rhs.unitsSold &&
lhs.revenue == rhs.revenue &&
lhs.sameIsbn(rhs);
}
inline
bool
operator!=(const salesItm &lhs, const salesItm &rhs)
{
return !(lhs == rhs);
}
// assumes that both objects refer to the same isbn
inline
salesItm&
salesItm::operator+=(const salesItm& rhs)
{
unitsSold += rhs.unitsSold;
revenue += rhs.revenue;
return *this;
}
// assumes that both objects refer to the same isbn
inline
salesItm
operator+(const salesItm& lhs, const salesItm& rhs)
{
salesItm ret(lhs); // copy lhs intoa local object that we'll return
ret += rhs; // add the ret(lhs) and rhs by overloaded operator +=
return ret; // return ret by value
}
using std::istream;
using std::ostream;
inline
istream&
operator>>(istream& in, salesItm& s)
{
double price;
in >> s.isbn >> s.unitsSold >> price;
if(in)
s.revenue = s.unitsSold * price;
else
s = salesItm();
return in;
}
inline
ostream&
operator<<(ostream& out, const salesItm& s)
{
out << s.isbn << "\t" << s.unitsSold << "\t" << s.revenue << "\t" << s.avgPrice();
return out;
}
#endif
The contents of cpp test file is shown as follow,
#include
#include "salesItem.h"
#include
using namespace std;
int main()
{
//salesItm book1("0-201-7863");
//salesItm book2("0-201-7863");
//salesItm book2 = book1;
salesItm b1("0-201-7863", 10, 200.0);
salesItm b2("0-201-7863", 20, 370.0);
salesItm b3("0-201-7863", 50, 400.0);
b1 += b2;
salesItm b4 = b2 + b3;
cout << "b1 + b2 = " << b1 << endl;
cout << "b2 + b3 = " << b4 << endl;
//if (book1.sameIsbn(book2)):
//{
//cout << "The books are the same." << endl;
//cout << "the avg price of book1 = " << book1.avgPrice() << endl;
//cout << book1 << endl;
//cout << book2 << endl;
//}
//else
//cout << "The books are not the same." << endl;
//cout << book1 << endl;
//cout << book2 << endl;
return 0;
}
REF: C++ Primer, 4th Edition