Creating and using the inserter and extractor functions builds on concepts introduced in previous chapters. Please review the following as needed:
Overloaded operators are "overloaded" because they define a new meaning for an operator to which the language has already assigned a meaning. Like overloaded functions, we can overload an operator many times, but we must observe two requirements. First, we may only overload an operator in the context of a new class, and second, at least one operand must be unique to distinguish the operator from the others. While these requirements apply to all overloaded operators, understanding them is especially important for using operator<< and operator>>.
Header File Requirement
The inserter and extractor operators, operator<< and operator>>, use two <iostream> classes, istream and ostream, as parameter types. Therefore, the class names appear in the functions' signatures in the class specification. When programmers overload either operator, they must include the <iostream> header before the class specification:#include <iostream> using namespace std;
We take an incremental approach, transitioning from "regular" functions to operators, to help us understand how operator<< and operator>> work. First, we explore two functions overloaded on a single parameter, followed by functions overloaded on two parameters.
void print(int x); print(3); |
void print(double x); print(3.14); |
void print(ostream& out, int x); print(cout, 5); |
void print(ostream& out, double x); print(cout, 5.7); |
(a) | (b) | (c) | (d) |
class ostream { public: friend ostream & operator<<(ostream &, char); friend ostream & operator<<(ostream &, char *); friend ostream & operator<<(ostream &, short); friend ostream & operator<<(ostream &, int); friend ostream & operator<<(ostream &, long); friend ostream & operator<<(ostream &, float); friend ostream & operator<<(ostream &, double); }; |
class istream { public: friend istream & operator>>(istream &, char &); friend istream & operator>>(istream &, char *); friend istream & operator>>(istream &, short &); friend istream & operator>>(istream &, int &); friend istream & operator>>(istream &, long &); friend istream & operator>>(istream &, float &); friend istream & operator>>(istream &, double &); }; |
(a) | (b) |
class string { public: friend ostream& operator<<(ostream& out, string& s); friend istream& operator>>(istream& in, string& s); }; |
class fraction { public: friend ostream& operator<<(ostream& out, fraction& f); friend istream& operator>>(istream& in, fraction& f); }; |
(c) | (d) |
(e.i) | (e.ii) |