Lesson 13 | Overloading I/O operators |
Objective | Overload input operator >> for card class. |
Overloading the C++ input Operator
istream& operator>>(istream& in, rational& x){
return (in >> x.a >> x.q);
}
Stream Input
As you know, the >> operator is used for stream input. This operator can also be overwritten to work with new data types.
For example, you can define an operator>> to read a Time object from an input stream. For simplicity, assume that the Time value is entered as three separate integers, such as
9 15 00
Here is the definition of the >> operator for Time objects:
istream& operator>>(istream& in, Time& a)
{
int hours;
int minutes;
int seconds;
in >> hours >> minutes >> seconds;
a = Time(hours, minutes, seconds);
return in;
}
Note that the second argument must be a non-const reference parameter, since it is modified when it is filled with the input.
The >> operator should return the input stream, just like the << operator. This allows a sequence of input operations to be
chained together, as they were for output, and as is illustrated in the body of the Time::operator>> function itself.
Peeking at the Input
The stream I/O library allows the programmer to peek ahead one character in the input; if you decide you don’t want the character you can put it back.
For example, suppose you want to write an input function for Fraction values. You want to allow the input to be either a simple integer (such as 7) or a
Fraction represented by an integer, a slash, and another integer (such as 3/4). If the next character after the numerator is not a slash, you want to push it back and return a Fraction with 1 as the denominator. You can write this function as follows:
istream& operator>>(istream& in, Fraction& r)
{
int t, b;
// Read the top
in >> t;
// If there is a slash, read the next number
char c;
in >> c;
if (c == '/')
in >> b;
else
{
in.unget();
b = 1;
}
r = Fraction(t, b);
return in;
}
Overloading Stream Extraction Operator - Exercise