Overloaded Operators as Non-Member friend Functions

The functions operator>> and operator<< are declared in PhoneNumber as non-member, friend functions (Fig. 10.3, lines 11–12). They’re non-member functions because the object of class PhoneNumber must be the operator’s right operand. If these were to be PhoneNumber member functions, the following awkward statements would have to be used to output and input a PhoneNumber:

phone << cout;
phone >> cin;

Such statements would be confusing to most C++ programmers, who are familiar with cout and cin appearing as the left operands of << and >>, respectively.

Overloaded operator functions for binary operators can be member functions only when the left operand is an object of the class in which the function is a member. Overloaded input and output operators are declared as friends if they need to access non-public class members directly or because the class may not offer appropriate get functions. Also, the PhoneNumber reference in function operator<<’s parameter list (Fig. 10.4, line 11) is const, because the PhoneNumber will simply be output, and the PhoneNumber reference in function operator>>’s parameter list (line 21) is non-const, because the PhoneNumber object must be modified to store the input telephone number in the object.


Image Software Engineering Observation 10.2

New input/output capabilities for user-defined types are added to C++ without modifying standard input/output library classes. This is another example of C++’s extensibility.


..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.219.42.240