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

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

本文关键字:错误 运算符 我的 超载 为什么 返回      更新时间:2023-10-16

所以我试图围绕运算符重载,我试图在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;进行defalut构造的,然后你得到的结果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;
}