Title | 7.8. Overloading comparison operators |
---|---|
Course | Intermediate Programming Methodologies in C++ - HONORS |
Institution | De Anza College |
Pages | 8 |
File Size | 522.3 KB |
File Type | |
Total Downloads | 73 |
Total Views | 132 |
7.8 Overloading comparison operators
Overloading the equality (==) operator
A programmer can overload the equality operator (==) to allow comparing objects of a programmer-defined class for equality. To overload ==, the programmer creates a function named operator== that returns bool and...
2/19/2021
7.8. Overloading comparison operators
7.8 Overloading comparison operators Overloading the equality (==) operator A programmer can overload the equality operator (==) to allow comparing objects of a programmer-dened class for equality. To overload ==, the programmer creates a function named operator== that returns bool and takes two const reference arguments of the class type for the left-hand-side and right-hand-side operands. Ex: To overload the == operator for a Review class, the programmer denes a function bool operator==(const Review& lhs, const Review& rhs). The programmer must also determine when two objects are considered equal. In the Review class below, two Review objects are equal if the objects have the same rating and comment. PARTICIPATION ACTIVITY
Start
7.8.1: Overloading the == operator.
2x speed
myReview
bestReview
bool operator==(const Review& lhs, const Review& rhs) { return (lhs.GetRating() == rhs.GetRating()) && (lhs.GetComment() == rhs.GetComment()); } ( == ) && 5 5 ( "Great" == "Great" ) true && true // ...
85
5
86
"Great"
rating
myReview
comment
87 88 89
5
90
"Great"
rating
bestReview
comment
true
if (myReview == bestReview) { cout currentRating; } // Sort reviews from lowest to highest sort(reviewList.begin(), reviewList.end()); cout...