Create a class Distance which contains data members as: kilometer, meter. Write C++ program to perform following functions: i. To accept a distance ii. To display a distance iii. To overload += operator to add two distances. iv. To overload > operator to compare two distances

//Note: If you are not using Borland or Turbo C then add the following line after header files :
//using namespace std;

#include<conio.h>
#include<iostream.h>
class distance
{
   int kilo,me; //kilo=kilometer , me=meter
   public:
   void accept();
   void display()
   {
    cout<<"\nyour distance is: "<<kilo<<" kilometer "<<me<<" meter";
   }
   void operator +=(distance d2)  //function overloading
   {
      d2.kilo+=kilo;

      d2.me+=me;
      if(d2.me>100)
      {
      d2.kilo=d2.kilo+1;
      d2.me=d2.me-100;
      }
      cout<<"\nAddition of 2 distance is: "<<d2.kilo<<" kilometer "<<d2.me<<" meter";

   }
   distance operator >(distance d2)  //function overloading
   {
    if(d2.kilo>kilo)
      {
      cout<<"\ndistance is greater: "<<d2.kilo;
      }
      else
      {
         cout<<"\ndistance is greater: "<<kilo<<" kilometer "<<me<<" meter";
      }
   }
};
void distance::accept()
{
cout<<"Enter kilometer: ";
   cin>>kilo;
   cout<<"Enter meter: ";
   cin>>me;
}
void main()
{
int ch;
distance d1,d2; //object created
   do{
   cout<<"\n1.Accept Distance\n2.Display Distance\n3.Add 2 Distance\n4.compare 2 Distance\n5.Exit\nEnter your choice:- ";
   cin>>ch;
   switch(ch)
   {
   case 1:
   d1.accept();
   d2.accept();break;
   case 2:
   d1.display();
   d2.display();break;
   case 3:
   d2+=d1;break;
   case 4:
   d2>d1; break;
   }
   }while(ch!=5);
}

0 Comments