Why does operator = return *this?

后端 未结 5 2259
感动是毒
感动是毒 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:59

    You return *this so you can write normal compound C++ = statements like:

    Poly p1; //an object representing a polynomial
    Poly p2;
    Poly p2;
    
    // ...
    
    p3 = p2 = p1;  //assigns all the contents of p1 to p2 and then to p3
    

    because that statement is basically:

    p3.operator=(p2.operator=(p1));
    

    If p2.operator=(...) didn't return *this you'd have nothing meaningful to pass into p3.operator=(...).

提交回复
热议问题