Overloading == operator C++
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
L开发者_JS百科ength 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);
}
For the simple case, use bool operator==(const Length& other) const
. Note the const
- a comparison operator shouldn't need to modify its operands. Neither should your operator+
!
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) {...}
Use bool and make sure to add const
as well.
bool operator==(const Length& lengthA) const { return ...; }
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:
bool operator== (const Length& lengthA, const Length& lengthB) const {
return (lengthA.min == lengthB.min) && (lengthA.max == lengthB.max);
}
Take a look at this: http://www.learncpp.com/cpp-tutorial/94-overloading-the-comparison-operators/
Cheers!
精彩评论