// USDollarAdd - demonstrate the definitiona and use // of the addition operator for the class // USDollar #include #include // USDollar - represent the greenback class USDollar { // make sure that the user defined operations have // access to the protected members of the class friend USDollar operator+(USDollar&, USDollar&); friend USDollar& operator++(USDollar&); public: // construct a dollar object with an initial // dollar and cent value USDollar(int d = 0, int c = 0); // rationalize - normalize the number of cents by // adding a dollar for every 100 cents void rationalize() { dollars += (cents / 100); cents %= 100; } // output- display the value of this object // to the standard output object void output() { cout << "$" << dollars << "." << cents; } protected: int dollars; int cents; }; USDollar::USDollar(int d, int c) { // store of the initial values locally dollars = d; cents = c; rationalize(); } //operator+ - add s1 to s2 and return the result // in a new object USDollar operator+(USDollar& s1, USDollar& s2) { int cents = s1.cents + s2.cents; int dollars = s1.dollars + s2.dollars; return USDollar(dollars, cents); } //operator++ - increment the specified argument; // change the value of the provided object USDollar& operator++(USDollar& s) { s.cents++; s.rationalize(); return s; } int main(int nArgc, char* pszArgs[]) { USDollar d1(1, 60); USDollar d2(2, 50); USDollar d3(0, 0); // first demonstrate a binary operator d3 = d1 + d2; d1.output(); cout << " + "; d2.output(); cout << " = "; d3.output(); cout << "\n"; // now check out a unary operator ++d3; cout << "After incrementing it equals "; d3.output(); cout << "\n"; return 0; }