Why does operator = return *this?

后端 未结 5 2257
感动是毒
感动是毒 2021-02-19 21:26

Say I want to override the operator = so I can do something like

Poly p1;  // an object representing a polynomial
Poly p2;  // another object of the         


        
5条回答
  •  死守一世寂寞
    2021-02-19 21:55

    p2 = p1 is a shorthand for p2.operator=(p1). It is just calling your operator= function, which is returning a reference to p2, which you are then ignoring. To make this clear, let's call it assign instead of operator=:

    Poly& Poly::assign(const Poly &source) {
        .
        .
        .
        return *this;
    }
    

    Now instead of p2 = p1, you would write

    p2.assign(p1);
    

    In this case, the result of calling assign is being ignored, but you don't have to ignore it. For example, you could write:

    p3.assign(p2.assign(p1));
    

    Using operator= instead of assign, this becomes

    p3 = (p2 = p1);
    

    but since assignment is right-associative, this can also be written as

    p3 = p2 = p1;
    

    This form of being able to do multiple assignments at once originally comes from C and has been preserved in C++ through the convention of returning *this in operator=().

提交回复
热议问题