Write a menu driven program for addition, subtraction, display result of two distances (given in meter and centimetre) . i. Overload ‘+’ operator with member function ii. Overload ‘–‘ operator using friend function iii. Overload << and >> operator

 


#include<iostream>
using namespace std;
class Distance
{
    private:
            int meter;
            int centimeter;
    public:
            Distance operator +(Distance &);
            Distance operator -(Distance &);
            friend istream & operator >>(istream &,Distance &);
            friend ostream & operator <<(ostream &,Distance &);

};


istream& operator >>(istream &in ,Distance &c)
{
    in>>c.meter;
    cout<<"meter"<<endl;
    in>>c.centimeter;
    cout<<"centimeter"<<endl;
    return(in);
}

 Distance Distance :: operator+ (Distance & m)
{
    Distance temp;
    temp.meter = meter+m.meter;
    temp.centimeter = centimeter + m.centimeter;
    if (temp.centimeter >= 100)
    {
        temp.centimeter=temp.centimeter-100;
        temp.meter++;
    }

    return temp;
}
Distance Distance :: operator -(Distance & m)
{
    Distance  temp;
    temp.meter = meter-m.meter;
    temp.centimeter = centimeter - m.centimeter;
    return temp;
}

ostream& operator <<(ostream &out ,Distance &c)
{
    out<<c.meter<<"meter and "<<c.centimeter<<"centimeter"<<endl;
    return(out);
}

int main()
{
    Distance d1,d2,d3,d4;
    cout<<"enter first distance in meter and in centimeter :"<<endl;
    cin>>d1;
    cout<<"enter second distance in meter and in centimeter :"<<endl;
    cin>>d2;
    d3=d1+d2;
    cout<<"addition of two distance is :"<<endl;
    cout<<d3;
    d4=d1-d2;
    cout<<"substraction of two distance is :"<<endl;
    cout<<d4;

}

output :

enter first distance in meter and in centimeter : 4 meter 67 centimeter enter second distance in meter and in centimeter : 2 meter 45 centimeter addition of two distance is : 7meter and 12centimeter substraction of two distance is : 2meter and 22centimeter


Comments

Popular Post

Define a class to represent a Bank Account. Include the following members: Data Members: i. Name of the depositor ii. Account number iii. Type of account iv. Balance amount in the account Member Functions: 1. To Input initial values 2. To deposit an amount 3. To withdraw an amount after checking the balance 4. To display name and balance Also write constructor for this class that takes four arguments. It should also handle type of account as savings by default