简体   繁体   中英

Overloading the << operator in C++ -why return type is a reference std::ostream&

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:

  1. define variables using an =
  2. pass it as an argument to a parameter of nonreference type
  3. return it from a function whose return type is nonreference
  4. initialize an array or an aggregate class using braces

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.

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