Overloading the Stream Extraction (>>) Operator

The stream extraction operator function operator>> (Fig. 10.4, lines 21–30) takes the istream reference input and the PhoneNumber reference number as arguments and returns an istream reference. Operator function operator>> inputs phone numbers of the form

(800) 555-1212

into objects of class PhoneNumber. When the compiler sees the expression

cin >> phone

in line 16 of Fig. 10.5, the compiler generates the non-member function call

operator>>( cin, phone );

When this call executes, reference parameter input (Fig. 10.4, line 21) becomes an alias for cin and reference parameter number becomes an alias for phone. The operator function reads as strings the three parts of the telephone number into the areaCode (line 24), exchange (line 26) and line (line 28) members of the PhoneNumber object referenced by parameter number. Stream manipulator setw limits the number of characters read into each string. When used with cin and strings, setw restricts the number of characters read to the number of characters specified by its argument (i.e., setw(3) allows three characters to be read). The parentheses, space and dash characters are skipped by calling istream member function ignore (Fig. 10.4, lines 23, 25 and 27), which discards the specified number of characters in the input stream (one character by default). Function operator>> returns istream reference input (i.e., cin). This enables input operations on PhoneNumber objects to be cascaded with input operations on other PhoneNumber objects or other data types. For example, a program can input two PhoneNumber objects in one statement as follows:

cin >> phone1 >> phone2;

First, the expression cin >> phone1 executes by making the non-member function call

operator>>( cin, phone1 );

This call then returns a reference to cin as the value of cin >> phone1, so the remaining portion of the expression is interpreted simply as cin >> phone2. This executes by making the non-member function call

operator>>( cin, phone2 );


Image Good Programming Practice 10.1

Overloaded operators should mimic the functionality of their built-in counterparts—e.g., the + operator should perform addition, not subtraction. Avoid excessive or inconsistent use of operator overloading, as this can make a program cryptic and difficult to read.


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

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