I just did a quiz for my programming class and got this question wrong:
The return t开发者_Python百科ype of the function to overload the operator
<<
must be a reference to an ostream object.
This does not seem right at all to me. Surely C++ is a bit more open ended than this. But I thought I'd ask here anyway. How is this right (or wrong)? My C++ knowledge begins to really fade when it comes to operator overloading..
It is not required by C++ that the return type be a reference to an ostream
object. However, if you are trying to do something like:
cout << instance_of_custom_type << 3 << "hi" << endl;
Then you will need:
ostream &operator << (ostream &os, custom_type &t);
However, if you were doing something like writing a large integer type, and wanted to support bit shifting, it might be something like:
BigInt operator << (const BigInt &i, unsigned int shift);
To expand this a bit further, the original use of the <<
operator is for bit shifting. 1 << 8
is 256, for example. C++ added a (slightly confusing) second use for this, and overloaded it on ostream
to mean "output" to the stream. You can do whatever you like within an overloaded operator - it works just like a function, however, operators have a human expectation attached with them: programmers expect, in C++, that <<
is bit shifting or stream output.
Having the return type as a refernce to the same stream object passed as reference argument to the overloaded insertion operator enables us to write code such as
mystream &operator << (mystream &os, myclass &myobject){
// do whatever
return os;
}
mystream << myobject << fundamental_type_object;
The return type of the function to overload the operator
<<
must be a reference to anostream
object.
To say 'must' is incorrect, probably 'usually' is the correct word, and why? Because as most of the answers have already pointed out, it gives the convenience of object chaining
, while working with iostreams
.
From the more general point of view, operator<<
should always return it's left hand side operand in order to chain calls, just like operator=
.
When dealing with the <iostreams>
library, this happens to be a reference to std::ostream
.
The purpose of having it return the ostream reference is so that you can chain them together. Otherwise you'd have to write cout << 1; cout << " is a number"; cout << endl
It isn't right. It's only correct in the context of iostreams, which in my probably irrelevant and uninteresting opinion should never have been let out of the cage in that form. If you don't include iostreams in your code you can do what you like. But I wouldn't be overloading these operators to do anything except shift classes, whatever that means, by integer values, or maybe by classes that can be reduced to integer values somehow.
精彩评论