C++:重载operator+=和operator-=时是否需要自赋值检查?

标签 c++ operator-overloading

重载 operator+=operator-= 时是否需要自赋值检查,如下例?

例子:

class A
{
     A operator+=(const A& a)
     {
         if(this != &a)
         {
             // operations
         }

         return *this;
     }
}

最佳答案

Is a self assignment check, as exampled below, required when overloading the operaators += and -= in C++?

不,不是。事实上,这样做似乎是错误的。

使用它是完全合法且语义上有效的:

int i = 10;
i += i;

此处的期望是 i 将在该操作结束时设置为 20

关于C++:重载operator+=和operator-=时是否需要自赋值检查?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35961292/

相关文章:

c++ - 好像我没有正确传递对象的指针,但为什么呢?

c++ - 如何使用结构作为条件的操作数?

c++ - 在抽象基类中重载运算符的正确方法是什么?

c++ - 如何让正则表达式匹配句子的中间?

c++ - 将代码声明转化为文字(引用运算符和取消引用运算符混淆)

c++ - googlemock 框架不适用于虚拟继承

c++ - + 运算符是否为原始类型重载?

c++ - 关闭管道时收到双重释放或损坏(顶部)?

c# - 允许使用多个系统显式转换器,但不允许使用多个用户显式转换器。为什么?

c++ - 为什么在上下文转换中不发生显式 bool() 转换