因此,我试图解决运算符重载问题,并试图在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;
}