简体   繁体   中英

C++ iostream operator overladed function return type

I'm still in learning phase of basic formats and commands of C++. I'm now at class operator function overloading and came to << and >> . My question is: when they are defined in friend functions such as below:

ostream &operator << ( ostream &output, const PhoneNumber &number )

and are called with PhoneNumber class phone like this:

cout << phone << endl;

Why is the friend function returning ostream& ? I mean when a function returns a value of a particular type, it is generally received by a fundamental type variable such as bool, int, char, string, and etc. However, for ostream and istream , the returned type of ostream& is not being saved. Then, in this case, shouldn't it be void (carry out the task and terminate without returning any values)?

Because otherwise you would be able to chain the calls to operator<< . This:

cout << phone << endl;

is parsed as:

(cout << phone) << endl;

and resolves as:

operator<<(cout, phone).operator<<(endl);

So it first calls operator<<(cout, phone) , which returns cout , which then allows the second << to call cout.operator<<(endl) .

If operator<< returned eg void , the second << would try to call operator<<(void, endl) which would not compile.

"Why is the friend function returning ostream& ?"

To make this part of the call chain working

phone << endl;

The ostream& reference is passed through all of these function calls, and thus the operator<<() function can be called again on the result.

Why is the friend function returning ostream&?

To allow operators to be chained together. The operators return a reference to the same stream that was passed in. Without that return reference, you would not be able to call << endl on the return value of cout << phone .

I mean when a function returns a value of a particular type, it is generally received by a fundamental type variable such as bool, int, char, string, and etc.

That is optional. A return value is temporary and goes out of scope at the end of the statement, if it is not assigned to a variable to extend its lifetime.

However, for ostream and istream, the returned type of ostream& is not being saved.

It does not have to be. It just has to stay alive long enough for the next operator to be called on it, if the final ; has not been reached yet.

Then, in this case, shouldn't it be void (carry out the task and terminate without returning any values)?

No.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM