gpt4 book ai didi

c++ - 为什么我的重载 "+"运算符返回错误的总金额?

转载 作者:行者123 更新时间:2023-11-28 01:14:08 27 4
gpt4 key购买 nike

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

关于c++ - 为什么我的重载 "+"运算符返回错误的总金额?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59258984/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com