Programmers frequently overload the inserter, operator<<, and the extractor, operator>>, because they are the main output and input functions for C++ programs. Each function follows a fixed pattern. While the pattern is rigid and unchanging, some elements are flexible and left to programmers to name. Specifically, programmers may choose the parameter names, and the class for which the operator is overloaded determines the type name of the second parameter. Everything else in the pattern is fixed and required. A simplified and highly abridged version of the fraction class demonstrates the patterns and the programmer-named elements.
friend ostream& operator<<(ostream& out, fraction & f) { // format and print f's members return out; } |
friend istream& operator>>(istream& in, fraction & f) { // read data into f's members return in; } |
return
the first parameterclass fraction { private: int numerator; int denominator; public: . . . friend ostream& operator<<(ostream& out, fraction& f); friend istream& operator>>(istream& in, fraction& f); . . private: void reduce(); }; |
ostream& operator<<(ostream& out, fraction& f) { out << f.denominator << "/" << f.numerator; return out; } istream& operator>>(istream& in, fraction& f) { cout << "Please enter the numerator: "; in >> f.numerator; cout << "Please enter the denominator: "; in >> f.denominator; reduce(); return in; } |
(a) | (b) |
fraction left; fraction right; cin >> left; cin >> right; fraction result = left + right; cout << result << endl; |
|
(c) | (d) |
friend
keyword is always a part of the function declaration, not the definition.
friend
keyword.The operator>> illustrated in (b) includes "Please enter . . ." prompts. The prompts make sense when a person responds by entering input through the console. However, an istream
can represent many input sources. The prompts are inappropriate when the input is automatic, for example, when a program reads input from a file or a device that doesn't require human interaction. In these cases, the prompt is unnecessary and potentially confusing. Furthermore, the prompts can negatively impact the program's performance.
Writing output to the console is a relatively slow process. The time needed to write a prompt is insignificant compared to the time needed for a person to enter the requested input. But, imagine the overloaded operator>> running in a loop. The numerous prompts "clutter" the screen and take a significant portion of the time needed to complete the input operation, slowing down the program. Generalizing the extractor is a better approach. The client program "knows" the data source and whether or not to prompt for input. Putting the prompts in the client code makes the extractor usable in diverse situations.