Why should the assignment operator return a reference to the object?

后端 未结 3 568
攒了一身酷
攒了一身酷 2020-11-27 06:38

I\'m doing some revision of my C++, and I\'m dealing with operator overloading at the minute, specifically the \"=\"(assignment) operator. I was looking online and came acro

3条回答
  •  死守一世寂寞
    2020-11-27 06:52

    The return type doesn't matter when you're just performing a single assignment in a statement like this:

    x = y;
    

    It starts to matter when you do this:

    if ((x = y)) {
    

    ... and really matters when you do this:

    x = y = z;
    

    That's why you return the current object: to allow chaining assignments with the correct associativity. It's a good general practice.

提交回复
热议问题