Overloaded '<' operator compares two Measures - C++ Class

C++ examples for Class:Operator Overload

Description

Overloaded '<' operator compares two Measures

Demo Code

#include <iostream>
using namespace std;
class Measure/* w  ww.ja  v a 2  s.c o m*/
{
   private:
       int feet;
       float inches;
   public:
       Measure() : feet(0), inches(0.0)
       {  }
       Measure(int ft, float in) : feet(ft), inches(in)
       {  }
       void getdist()              //get length from user
       {
          cout << "\nEnter feet: ";  cin >> feet;
          cout << "Enter inches: ";  cin >> inches;
       }
       void showdist() const
       { cout << feet << "\'-" << inches << '\"'; }
       bool operator < (Measure) const; //compare distances
};
//compare this distance with d2
bool Measure::operator < (Measure d2) const  //return the sum
{
   float bf1 = feet + inches/12;
   float bf2 = d2.feet + d2.inches/12;
   return (bf1 < bf2) ? true : false;
}
int main()
{
   Measure dist1;                 //define Measure dist1
   dist1.getdist();                //get dist1 from user
   Measure dist2(6, 2.5);         //define and initialize dist2

   cout << "\ndist1 = ";  dist1.showdist();
   cout << "\ndist2 = ";  dist2.showdist();
   if( dist1 < dist2 )             //overloaded '<' operator
      cout << "\ndist1 is less than dist2";
   else
      cout << "\ndist1 is greater than (or equal to) dist2";
   cout << endl;
   return 0;
}

Result


Related Tutorials