为什么我超载的“+”运算符返回错误的总金额?

Why is my overloaded "+" operator returning the wrong total amount?

所以我正在努力解决运算符重载问题,并且正在尝试在 main() 中添加两个实例化框的长度和高度。问题是总数应该是 myBox(2,4) + myBox2(1,2) = (3,6),但输出总数错误地显示“2 / 3”。

#include<iostream>

using namespace std;

class Box {

    public:
        int length, height;
        Box(){ 
            length = 1, height = 1;
        }
        Box(int l , int h) {
            length = l, height = h;
        }
        Box operator +(const Box& boxToAdd) {
            Box boxSum;
            boxSum.length = boxSum.length + boxToAdd.length;
            boxSum.height = boxSum.height + boxToAdd.height;
            return boxSum;
        }
    };


    ostream& operator<<(ostream& os, const Box& box) {
    os << box.length << " / " << box.height << endl;
        return os;

    }
    int main() {
        Box myBox(2,4);
        cout << "First box length and height: "<<myBox << endl; // Outputs length and height data member values.
        Box myBox2(1, 2);
        cout << "Second box length and height: " << myBox2 << endl;

        cout << "The total of both boxes is: " << myBox + myBox2 << endl;
        cin.get();
}

operator+ 中,您正在执行 boxSum 的加法;这是刚才用 length = 1, height = 1; 默认构造的,然后你得到结果 2 (1 + 1) 和 3 (2 + 1)。您应该从当前实例执行加法。例如

Box operator +(const Box& boxToAdd) {
    Box boxSum;
    boxSum.length = this->length + boxToAdd.length;
    boxSum.height = this->height + boxToAdd.height;
    return boxSum;
}

LIVE