operator overloading using ostream and chaining. Why return by reference?

后端 未结 5 1095
粉色の甜心
粉色の甜心 2021-02-10 19:24

There are many questions and answers for this, but I can\'t really find why we need to return by reference.

If we have (assume operator is already correctly ov

5条回答
  •  北海茫月
    2021-02-10 19:58

    here is one interesting answer i founded on learncpp.com

    ostream is a class provided as part of C++ that handles outputs streams. The details of how ostream is implemented is very complex, but fortunately also completely unnecessary to use it effectively.

    Since ostream is a class, ostream& is a reference to an ostream class. Note that we’re also taking an ostream& as a parameter. ostream is typically passed by reference because we don’t want to make a copy of it as we pass it around.

    So basically, our overloaded function takes an ostream as a parameter, writes stuff to it, and then returns the same ostream. This allows us to chain << calls together:

    cout << cPoint1 << cPoint2 << cPoint3;
    

    This resolves as follows:

    ((cout << cPoint1) << cPoint2) << cPoint3;
    

    cout < < cPoint1 is resolved first, with cout becoming the ostream& parameter. When this overloaded function is finished writing to the out parameter, it returns that cout so the next call to << can use it. Thus:

    ((cout << cPoint1) << cPoint2) << cPoint3;
    

    becomes:

    (cout << cPoint2) << cPoint3;
    

    becomes:

    cout << cPoint3;
    

    This calls our overloaded function one last time. At the end of this function, cout is again returned. But there's nobody left to use it, so the return value is ignored. The expression ends, and the program moves to the next line.

提交回复
热议问题