为什么我的超载"+"运算符返回的总额错误?
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;
进行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;
}
住
相关文章:
- 在运算符重载定义中使用成员函数(const错误)
- 逻辑运算符上出现错误代码 a')'
- 错误 C2679:二进制"<<":未找到采用类型 'std::string_view' 的右侧操作数的运算符(或者没有可接受的转换)
- C++:需要帮助了解运算符重载错误
- 我在 .h 中有一个枚举类,并且在.cpp错误中有一个运算符重载:与"运算符<<不匹配
- C++分数混合比较运算符错误
- 为什么我收到错误:"运算符<<不匹配?
- 迭代器类的重载前缀增量运算符会引发分段错误
- 在 boost::qi 中使用过多的替代运算符会导致分段错误
- 调用运算符时出现链接器错误<<,如何解决?
- 错误:表达式必须具有算术、无作用域枚举或带有运算符重载的指针类型
- 解决错误:运算符 [] 不匹配
- 提升错误:"运算符=="的重载不明确
- 字符串输入中没有匹配的错误运算符错误
- 错误:运算符 = IN C++ 不匹配
- QT 创建器错误(运算符 + 不匹配)
- 错误C++运算符重载
- 错误:运算符==不匹配
- C++ 语法和编译器错误 - 运算符不匹配<<
- C++错误--运算符=不匹配