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

后端 未结 5 1105
粉色の甜心
粉色の甜心 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 20:05

    Blah Blah::operator =(Blah rhs){
    Blah ret;
    ret.x = rhs.x;
    ret.y = rhs.y;
    return ret;
    }-->(1)
    
    Blah b1(2,3);
    Blah b2(4,1);
    Blah b3(8,9);
    Blah b4(7,5);
    

    b3 = b4 = b2 = b1;---->(2)

    By invoking (2) you will call =() and Here in the above snippet(1) you are returning a temporary object .Note that you are not updating the x value of the actual object.For eg operation starts like this b2(x,y) = b1(2,3) and you are initialising the value 2 & 3 in the temporary object ret and returning the temporary object by value .so that temporary object is now going to invoke b4 ie b4 = temp(2,3) and again the same funda.you will copy 2 & 3 to b4 and returns a temp object which is invoking b3 as b3 = temp(2,3).Now if you replace (2) like this printed cout << b3=b4=b2=b1 (provided implement << overloading),you would have got 2 & 3 as output because 2 & 3 will be avilable only in this line.In your example you are printing in the next lines where this value is not available only because you are not updating the value of x & y in the object which invoked .So for that to work out you should return *this as a reference which means you are returning the object which invoked the function .SO if you do b2=b1 and return *this ,ie means you are returning the actual object and x,y value of actual object is getting updated and it will be available as long as the object exists.

提交回复
热议问题