I'm reading this tutorial about overloading the <<
operator in C++.
I'm trying to understand why the return type is a reference std::ostream&
? The tutorial says that
if you try to return std::ostream by value, you'll get a compiler error. This happens because std::ostream specifically disallows being copied.
Could somebody explain whwere std::ostream
is being copied?
std::ostream& operator<< (std::ostream &out, const Point &point)
{
// Since operator<< is a friend of the Point class, we can access Point's members directly.
out << "Point(" << point.m_x << ", " << point.m_y << ", " << point.m_z << ")";
return out;
}
In C++, an object is copied when you:
By the 3rd case, 'out' will be copied if the return type is std::ostream
. So it should be std::ostream&
. (You may notice that the type of the first parameter is also std::ostream&
, avoiding copy)
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.