lecture9 notes

# Dollars dollars odollars 5 6 iftmpcents 100 7

This preview shows page 1. Sign up to view the full content.

This is the end of the preview. Sign up to access the rest of the document.

Unformatted text preview: the addition operator by overloading the addition operator. This can be done either inside the class as part of its definition (the addition from the point of view of the object on the left side of the +): 1 2 3 4 USCurrency operator+(const USCurrency o) { USCurrency tmp = {0, 0}; tmp.cents = cents + o.cents; tmp.dollars = dollars + o.dollars; 5 6 if(tmp.cents >= 100) { 7 tmp.dollars += 1; 8 tmp.cents -= 100; 9 } 10 11 return tmp; 12 } or outside the class as a function independent of the class (the addition from the point of view of the +): 1 USCurrency operator+(const USCurrency m, const USCurrency o) { 2 USCurrency tmp = {0, 0}; 3 tmp.cents = m.cents + o.cents; 4 tmp.dollars = m.dollars + o.dollars; 5 6 if(tmp.cents >= 100) { 7 tmp.dollars += 1; 8 tmp.cents -= 100; 9 } 10 11 return tmp; 12 } Similarly, we can overload the << operator to display the result: 1 ostream& operator<<(ostream &output, const USCurrency &o) 2 { 3 output << "\$" << o.dollars << "." << o.cents; 4 return output; 5 } Assuming the above definitions, we can run the following program: 1 int main() { 2 USCurrency a 3 USCurrency b 4 USCurrency c 5 cout << c << 6 return 0; 7 } = {2, 50}; = {1, 75}; = a + b; endl; and get the printout \$4.25. The list of overloadable operators: + = << == >> () * < <<= , / > >>= ->* += <= & -> -= >= ^ new *= ! | new /= % != && &= ^= delete %= ++ || |= ~ delete - -...
View Full Document

## This document was uploaded on 03/18/2014 for the course EECS 6.096 at MIT.

Ask a homework question - tutors are online