why this code dont work? why do i need the return type to be a reference?
ostream operator<<(ostream& os, class n);
i need to know whats happening inside and why it doesnt work if the return type is not a reference. And i need some links to good articles about istreams and ostreams that help me understand them (not too complicated articles please :D:D) than开发者_StackOverflow社区k you very much.
UPDATE 1: please remember to share links for articles so i can learn more about ostream and istream objects. thank you.
ostream
is not a copyable type.
std::ostream
's copy constructor is private - which means you cannot create a copy of a stream object.
Each stream has an associated underlying buffer - which handles the reads/writes (for example filebuf
manages the reads/writes to files). If you were to make a copy of the stream, what do you propose to do with this underlying buffer? You cannot copy it, because then you would have two buffers (maintaining separate positional information - e.g. where it's written to) - imagine the havoc... If you "move" it - i.e. transfer the ownership, there is the potential that you could quite conceivably loose the buffer (if copied to some scoped stream - say you pass it by value to a function and don't return it), then what happens? It's for complications like these, it makes sense to make this object non-copyable...
Because ostream
is noncopyable
class. This is by design, just like threads and other concepts that are noncopyable.
Typically when you override operator<< it will look like something approximating this:
ostream& operator<<(ostream& os, class n)
{
os << n.some_data() << n.some_other_data();
return os;
}
If you dont return the ostream as a reference, you wont be able to do this:
n myclass;
std::cout << myclass << std::endl;
The return type has to be a reference to the same stream os so that you can chain calls together. For example:
out << "hello" << " " << "world";
If it wasn't a reference, the return type would be a value. Each value is a different stream, and so "hello" and "world" would go to different places. The references all refer to the same identical stream, so "hello" and "world" get output to the same place.
精彩评论