重载 == 运算符 C++
我重载了 + 运算符,但现在我想重载 2 个长度的 == 运算符(长度可能相同,也可能不同)并返回各自的结果。我该怎么做?我需要使用 bool 来表示 == 吗?
//我做了什么来重载+运算符以从2个不同的长度中获取新的长度
Length operator+ (const Length& lengthA){
int newlengthMin = min, newlengthMax = max;
if (lengthA.min < min)
newLengthMin = lengthA.min;
if (lengthA.max > max)
newLengthMax = lengthA.max;
return Length(newLengthMin, newLengthMax);
}
i did an overloading of the + operator but now i wanna do overloading of == operator of 2 lengths (may or may not be the same length) and return the respective results. How do i do it? Do i need to use bool for ==?
//what i did for overloading + operator to get new length out of 2 different lengths
Length operator+ (const Length& lengthA){
int newlengthMin = min, newlengthMax = max;
if (lengthA.min < min)
newLengthMin = lengthA.min;
if (lengthA.max > max)
newLengthMax = lengthA.max;
return Length(newLengthMin, newLengthMax);
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
对于简单情况,请使用bool运算符==(const Length& other) const。请注意
const
- 比较运算符不需要修改其操作数。你的operator+
也不应该!如果要利用两侧的隐式转换,请在全局范围内声明比较运算符:
bool operator==(const Length& a, const Length& b) {...}
For the simple case, use
bool operator==(const Length& other) const
. Note theconst
- a comparison operator shouldn't need to modify its operands. Neither should youroperator+
!If you want to take advantage of implicit conversions on both sides, declare the comparison operator at global scope:
bool operator==(const Length& a, const Length& b) {...}
使用 bool 并确保添加
const
。您还可以使用两个参数(每个对象一个)将其设置为全局。
Use bool and make sure to add
const
as well.You can also make it global, with two arguments (one for each object).
是的,相等运算符是比较运算。您将返回一个指示正确条件的布尔值。它会是这样的:
Yes, the equality operator is a comparison operation. You'll return a boolean indicating the correct condition. It would be something like this:
看看这个:
http://www.learncpp.com/cpp-tutorial/ 94-重载-比较运算符/
干杯!
Take a look at this:
http://www.learncpp.com/cpp-tutorial/94-overloading-the-comparison-operators/
Cheers!