The stream extraction (>>) and insertion (<<) operators can be overloaded for performing input and output operations.
So far, in order to display a Rational object, you invoke the toString() function to return a string representation for the Rational object and then display the string. For example, to display a Rational object r, you write
cout << r.toString();
Wouldn’t it be nice to be able to display a Rational object directly using a syntax like the following?
cout << r;
The stream insertion operator (<<) and the stream extraction operator (>>) are just like other binary operators in C++. cout << r is actually the same as <<(cout, r) or operator<<(cout, r).
Consider the following statement:
r1 + r2;
The operator is + with two operands r1 and r2. Both are instances of the Rational class. So, you can overload the + operator as a member function with r2 as the argument. However, for the statement
cout << r;
the operator is << with two operands cout and r. The first operand is an instance of the ostream class, not the Rational class. So, you cannot overload the << operator as a member function in the Rational class. However, you can define the function as a friend function of the Rational class in the Rational.h header file:
friend ostream& operator<<(ostream& out, const Rationa1& rational);
Note that this function returns a reference of ostream, because you may use the << operator in a chain of expressions. Consider the following statement:
cout << r1 << ” followed by ” << r2;
This is equivalent to
((cout << r1) << ” followed by “) << r2;
For this to work, cout << r1 must return a reference of ostream. So, the function << can be implemented as follows:
ostream& operator<<(ostream& out, const Rational& rational)
{
out << rational.numerator << “/” << rational.denominator; return out;
}
Similarly, to overload the >> operator, define the following function header in the Rational.h header file:
friend istream& operator>>(istream& in, Rational& rational);
Implement this function in Rational.cpp as follows:
istream& operator>>(istream& in, Rationa1& rational)
{
cout << “Enter numerator:
in >> rational.numerator;
cout << “Enter denominator: “;
in >> rational.denominator;
return in;
}
The following code gives a test program that uses the overloaded << and >> functions operators.
1 Rational r1, r2;
2 cout << “Enter first rational number” << endl;
3 cin >> r1;
4
5 cout << “Enter second rational number” << endl;
6 cin >> r2;
7
8 cout << r1 << ” + ” << r2 << ” = ” << r1 + r2 << endl;
Line 3 reads values to a rational object from cin. In line 8, r1 + r2 is evaluated to a new rational number, which is then sent to cout.
Source: Liang Y. Daniel (2013), Introduction to programming with C++, Pearson; 3rd edition.