C++ : overloading assignment operator +=


#include<iostream>

using namespace std;

class dist
{
private:
    int feet;
    float inches;
public:
    dist():feet(0),inches(0){}
    dist(int f,float in):feet(f),inches(in){}

    void getdist()
    {
        cout<<"feet:";cin>>feet;
        cout<<"inches:";cin>>inches;
    }

    void operator +=(dist d2);
    friend void showdist(dist d);
};

void showdist(dist d)
{
    cout<<d.feet<<"\'-"<<d.inches<<"\""<<endl;
}

void dist::operator+=(dist d2)
{
    feet=feet+d2.feet;
    inches+=d2.inches;
    if(inches>=12)
    {
        inches-=12;
        feet++;
    }
}

int main()
{
    dist d1(7,7.25);
    dist d2;
    d2.getdist();
    d1+=d2;
    cout<<"_______________________________________\n\n\n";
    cout<<"d1 after addition with d2 is:";
    showdist(d1);
    dist d3(4,7.5);
    d1+=d3;//if d1+=d2+d3 is written then '+' should be overloaded
    cout<<"d1 after addition with d3 is:";
    showdist(d1);
    return 0;
}

No comments:

Post a Comment