Overloading assignment operator in C++

后端 未结 10 1167
春和景丽
春和景丽 2020-11-30 04:48

As I\'ve understand, when overloading operator=, the return value should should be a non-const reference.


A& A::operator=( const A& )
{
    // check for sel         


        
10条回答
  •  攒了一身酷
    2020-11-30 05:48

    If it returned a copy, it would require you to implement the copy constructor for almost all non-trivial objects.

    Also it would cause problems if you declare the copy constructor private but leave the assignment operator public... you would get a compile error if you tried to use the assignment operator outside of the class or its instances.

    Not to mention the more serious problems already mentioned. You don't want it to be a copy of the object, you really do want it to refer to the same object. Changes to one should be visible to both, and that doesn't work if you return a copy.

提交回复
热议问题