Suppose I have a struct called HeightType that stores a person's height using two fields: feet and inches. Write an overloaded operator for the > sign that will return true if the first HeightType value is greater than the second one.
1
Expert's answer
2013-02-19T07:33:33-0500
//====================================================== // overload operator '>' //====================================================== bool operator>(HeightType & a, HeightType & b){ // if fields 'feet'coincide, then we should compare fields 'inches' if (a.feet ==b.feet) { return(a.inches>b.inches); } return (a.feet> b.feet); } //======================================================
Below is an example of usage
#include <iostream> struct HeightType { int feet; int inches; HeightType(intf, int i) { feet=f; inches=i; } };
// overload operator '>' bool operator>(HeightType & a, HeightType & b) { // if fields'feet' coincide, then we should compare fields 'inches' if (a.feet ==b.feet) { return(a.inches>b.inches); } return (a.feet> b.feet); }
int main() { // now a>b HeightType a =HeightType(11,6); HeightType b =HeightType(11,5);
if (a>b) { std::cout<< "a > b "; } else { std::cout<< "a <= b "; }; return 0; }
Comments
Leave a comment