Limitation to overloaded + operator - C++ Class

C++ examples for Class:Operator Overload

Description

Limitation to overloaded + operator

Demo Code

#include <iostream>
using namespace std;
class Measure/*www  . ja  va2s . c  o  m*/
{
   private:
   int feet;
   float inches;
   public:
   Measure() : feet(0), inches(0.0)
   {  }                            //constructor (one arg)
   Measure(float fltfeet)     //convert float to Measure
   {                        //feet is integer part
       feet = static_cast<int>(fltfeet);
       inches = 12*(fltfeet-feet); //inches is what's left
    }
    Measure(int ft, float in)
    { feet = ft; inches = in; }
    
    void showdist()
    { cout << feet << "\'-" << inches << '\"'; }
    
    Measure operator + (Measure);
};
//add this distance to d2
Measure Measure::operator + (Measure d2)   //return the sum
{
    int f = feet + d2.feet;        //add the feet
    float i = inches + d2.inches;  //add the inches
    if(i >= 12.0)                  //if total 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: ERROR
    // cout << "\nd3 = "; d3.showdist();
    cout << endl;
    return 0;
}

Result


Related Tutorials