Why does operator = return *this?

后端 未结 5 2197
感动是毒
感动是毒 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 22:13

    what happens when you return *this?

    In your example (p2 = p1;), nothing. The method copies p1 into p2 and returns a reference to the 'this' object, which the calling code doesn't use.

    In code such as p3 = p2 = p1;, the first invocation is p2 = p1, which copies p1 into p2 and returns a reference to p2. The calling code then copies from that reference-to-p2 into p3 (and ignores the reference to p3 that is returned).

    (In passing: do your unit tests ensure that p1 = p1 works properly? It's easy to forget that case!)

提交回复
热议问题