Operator overloading

I don't quite understand the code from line 20 to 24 when it is trying to overload the << operator. Can anyone please explain it to me? Thank You

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
  class USCurrency {
int dollars;
int cents;
};


USCurrency operator+(const USCurrency m, const USCurrency o) {
     USCurrency tmp = {0, 0};
 tmp.cents = m.cents + o.cents;
 tmp.dollars = m.dollars + o.dollars;

 if(tmp.cents >= 100) {
 tmp.dollars += 1;
 tmp.cents -= 100;
 }

 return tmp;
 }

 ostream& operator<<(ostream &output, const USCurrency &o)
 {
 output << "$" << o.dollars << "." << o.cents;
 return output;
 }
 
 int main() {
 USCurrency a = {2, 50};
 USCurrency b = {1, 75};
 USCurrency c = a + b;
 cout << c << endl;
 return 0;
 }


this function overloads the operator<< to be able to write something like:
1
2
3
USCurrency o;
          //initialising o
          cout<<o;

ostream is the type of cout
and line 22 is like saying
cout<<"$" << o.dollars << "." << o.cents;
In line 20, the function argument ostream &output essentially tells that "output" is an ostream object, you can simply consider it as output == cout, so in line 22 is same as cout << "$" << o.dollars << "." << o.cents;

Similarly, you can also define istream, like istream& input, which basically means that input == cin, so you can use input >> something instead of cin >> something.
Topic archived. No new replies allowed.