obj.operator + =rhs与obj + = rhs

问题描述

class test
{
public:
    int i = 0;
    test& operator+=(const test &rhs)
    {
        i += rhs.i;
        return *this;
    }
};

int main()
{ 
    test t;
    test rhs;
    rhs.i = 10;
    // what's the difference betwen these 2?
    t.operator+=(rhs);
    t += rhs;
}

这里的t.operator+=(rhs);t += rhs;有什么区别吗?我一直都使用后者,而对于前者却从未考虑太多。与前者相比,使用前者有什么优势吗?

解决方法

在大多数情况下,没有区别。当您写时:

t += rhs

编译器将其处理为:

t.operator+=(rhs)

因此,这两个调用只是同一调用的不同语法。