Calculate DIstance with overload binary and unary


Program to create class distance with number of feet & inches,overload binary(+,-),unary(++,--) in C++





#include<iostream.h>
#include<conio.h>
class Distance
{
float feet,inches;
public:
  Distance()
  {
  }
  Distance(float f,float i)
  {
    feet=f;
    inches=i;
  }
Distance operator+(Distance X)
  {
    Distance temp;
    temp.feet=feet+X.feet;
    temp.inches=inches+X.inches;
    temp.feet=temp.feet+int(temp.inches)/12;
    temp.inches=(int)temp.inches%12;
    return(temp);
  }
  Distance operator-(Distance X)
  {
    Distance temp;
    temp.feet=feet-X.feet;
    temp.inches=inches-X.inches;
    temp.feet=temp.feet-int(temp.inches)/12;
    temp.inches=(int)temp.inches%12;
    return(temp);
  }
  void operator++()
  {
    inches++;
    if(inches>=12)
    {
      feet++;
      inches=0;
    }
  }
  void operator--()
  {
    inches--;
    if(inches<=0)
    {
      feet--;
      inches=0;
    }
  }
  void display()
  {
    cout<<"\nDistance is "<<feet<<"feet "<<inches<<"inches"<<endl;
  }
};
void main()
{
clrscr();
Distance D1(10,10),D2(20,20);
Distance D3;
D1.display();
D2.display();
D3=D1+D2;
D3.display();
D3++;
D3.display();
D3=D2-D1;
D3.display();
D3--;
D3.display();
getch();
}


OUTPUT
Distance in 10 feet 10 inches
Distance in 20 feet 20 inches
Distance in 32 feet 6 inches
Distance in 32 feet 7 inches
Distance in 10 feet 10 inches
Distance in 10 feet 9 inches


-----

Firoz Memon

Please view my other blogs:

          C++ Codes 4 Beginners

          Java Tips

          Java 4 Beginners

Previous Post Next Post