Overloading operators

 

Overloading the plus operator

Distance Distance:: operator + (Distance rhs)
{
        Distance temp;
        temp.feet = feet + rhs.feet;
        temp.inches = inches + rhs.inches;
        if (temp.inches >=12)
        {       temp.inches -=12;
                temp.feet++;
        }
        return temp;
}

 

 

Overloading the > operator

Overloading the += operator

Overload the << and >> operators

      This lets you input and output object like basic types

      We would like to be able to say:
  cout << d1;  or
  cin >> d2
instead of call functions to do the I/O

 

The ostream class

      When we overload the << operator, we must return a reference to an object of type ostream

      If we overload << for the Distance class, it looks like this:

  ostream& operator << (ostream& s, Distance& d)
{  s << d.feet << " feet " << d.inches << " inches ";
    return s  }

      The problem with this is that it must directly access Distance data members, but is not part of the Distance class

    So in the header, we declare it a friend function.

      This enables us to say cout << d1;

 

Friends

      To do this, you use the keyword friend with the prototype of the function to be declared a friend

      This goes in the header, within the class declaration

      Example:

   friend ostream& operator << (ostream& s,
                                                   Distance& d);

      Both classes and functions can be declared friends to a class

 

The istream class

      When we overload the >> operator, we must return a reference to an object of type istream

      Overloading the >> operator for the Distance class
istream& operator >> (istream& s, Distance& d)
{     cout << " \nEnter feet: " ;    s >> d.feet;
       cout << " Enter inches: ";   s >> d.inches;
       return s;
}

      This function must also be declare a friend to the Distance class