C++ Operator Overload << and >> operators

Description

C++ Operator Overload << and >> operators

#include <iostream>
using namespace std;
class Measure/*  w  w  w.j a  va  2  s .co  m*/
{
   private:
   int feet;
   float inches;
   public:
   Measure() : feet(0), inches(0.0)
   {  }
   Measure(int ft, float in) : feet(ft), inches(in)
   {  }
   friend istream& operator >> (istream& s, Measure& d);
   friend ostream& operator << (ostream& s, Measure& d);
};
istream& operator >> (istream& s, Measure& d)  //get Measure
{
   cout << "\nEnter feet: ";  s >> d.feet;      //using
   cout << "Enter inches: ";  s >> d.inches;    //overloaded >> operator
   return s;
}
ostream& operator << (ostream& s, Measure& d)  //display
{                                            //Measure
s << d.feet << "\'-" << d.inches << '\"';    //using overloaded << operator
return s;
}
int main()
{
    Measure dist1, dist2;
    Measure dist3(11, 6.25);       //define, initialize dist3
    cout << "\nEnter two Measure values:";
    cin >> dist1 >> dist2;          //get values from user
    s
    cout << "\ndist1 = " << dist1 << "\ndist2 = " << dist2;
    cout << "\ndist3 = " << dist3 << endl;
    return 0;
}



PreviousNext

Related