Using friend function to overload + operator - C++ Class

C++ examples for Class:friend

Description

Using friend function to overload + operator

Demo Code

#include <iostream>
using namespace std;
class Measure/*from   w  w  w.  ja va2 s.c  om*/
{
   private:
   int feet;
   float inches;
   public:
   Measure()
   { feet = 0; inches = 0.0; }
   Measure( float fltfeet )   //constructor (one arg)
   {                        //convert float to Measure
       feet = int(fltfeet);           //feet is integer part
       inches = 12*(fltfeet-feet);    //inches is what's left
   }
   Measure(int ft, float in)
   { 
       feet = ft; inches = in; 
   }
    
   void showdist()
   { cout << feet << "\'-" << inches << '\"'; }
    
    friend Measure operator + (Measure, Measure); //friend
};

Measure operator + (Measure d1, Measure d2) //add D1 to d2
{
    int f = d1.feet + d2.feet;        //add the feet
    float i = d1.inches + d2.inches;  //add the inches
    if(i >= 12.0)                  //if inches exceeds 12.0,
       { i -= 12.0; f++;  }        //less 12 inches, plus 1 foot
    return Measure(f,i);          //return new Measure with sum
}
int main()
{
    Measure d1 = 2.5;                //constructor converts
    Measure d2 = 1.25;               //float-feet to Measure
    Measure d3;
    cout << "\nd1 = "; d1.showdist();
    cout << "\nd2 = "; d2.showdist();
    d3 = d1 + 10.0;                   //distance + float: OK
    cout << "\nd3 = "; d3.showdist();
    d3 = 10.0 + d1;                   //float + Measure: OK
    cout << "\nd3 = "; d3.showdist();
    cout << endl;
    return 0;
}

Result


Related Tutorials