添加具有已定义运算符的对象并不像我预期的那样工作

Adding objects with defined operator doesn't work as I expect

输出等于 20。为什么 return 值不是 30?

class Myclass
{
public:
    int result;

    Myclass() { result = 10; }

    Myclass operator+ (Myclass& obj) {
        Myclass tempObj;
        tempObj.result += obj.result;
        return tempObj;
    }
};

int main()
{
    Myclass obj1, obj2, obj3;
    cout << (obj1 + obj2 + obj3).result;
}

如果我理解正确,obj2 + obj3 return tempObj 结果 = 20。下一步是加法 tempObj + obj1,应该再次 return tempObj 但结果 = 30。

operator+从左到右执行,则obj1 + obj2 + obj3解释为(obj1 + obj2) + obj3,即先执行obj1 + obj2obj1 + obj2返回的临时对象包含result20,则operator+以临时对象为左操作数,obj3为右操作数执行。在operator+中,根本不使用左操作数(即*this),它总是对局部对象tempObj(其result10) 和右操作数(obj3result 也是 10),然后你得到结果 20.

operator+ 应该对左右操作数执行加法。例如

Myclass operator+ (Myclass& obj) {
    Myclass tempObj(*this);
    tempObj.result += obj.result;
    return tempObj;
}

Myclass operator+ (Myclass& obj) {
    Myclass tempObj;
    tempObj.result = this->result + obj.result;
    return tempObj;
}

运算符内

Myclass operator+ (Myclass& obj) {
    Myclass tempObj;
    tempObj.result += obj.result;
    return tempObj;
}

已创建本地对象 tempObj,其数据成员 result 始终由 10 初始化。

所以虽然子表达式创建的临时对象

obj1 + obj2

数据成员 result 等于 20 然而它的值被忽略。

你的意思好像是

Myclass operator+ (Myclass& obj) {
    Myclass tempObj( *this );
    tempObj.result += obj.result;
    return tempObj;
}

注意参数要有常量引用类型,运算符本身要常量。例如

Myclass operator+ ( const Myclass& obj) const {
    Myclass tempObj( *this );
    tempObj.result += obj.result;
    return tempObj;
}