Wednesday, 8 January 2014

Program of Operator overloading

/*Program of Operator overloading*/
#include<iostream>
using namespace std;
class A
{
    int hr,mn,ss;
public:
    A();
    A(int h,int m,int s);
    void display();
    A  operator -();    //Unary
    A operator +(A);    //Binary
    A operator ++();
    int operator ==(A);
    A operator +=(A);
    A operator =(A);
};
A::A()
{
    hr=0; mn=0; ss=0;   
}
A::A(int h,int m,int s)
{
    ss=s; mn=m; hr=h;           
}
void A::display()
{       
    mn=mn+ss/60;
    hr=hr+mn/60;
    ss=ss%60;
    mn=mn%60;
    cout<<hr<<":"<<mn<<":"<<ss<<endl;
}
A  A::operator -()
{
    hr=-hr; mn=-mn; ss=-ss;
    return *this;
}
A A::operator +(A x)
{
    A temp;
    temp.hr=hr+x.hr;
    temp.mn=mn+x.mn;
    temp.ss=ss+x.ss;
    return temp;
}
A A:: operator ++()
{
    ++hr; ++mn; ++ss;
    return *this;
}
int A:: operator ==(A x)
{
    if(hr==x.hr && mn==x.mn && ss==x.ss)
        return 1;
    else
        return 0;
}
A A:: operator +=(A x)
{
    hr=hr+x.hr;
    mn=mn+x.mn;
    ss=ss+x.ss;
    return *this;
}
A A:: operator =(A x)
{
    hr=x.hr;
    mn=x.mn;
    ss=x.ss;
    return *this;
}

main()
{
    int result;
    A t1(15,70,188),t2(11,1,2),t3,t4;
    t1.display();
    -t1;
    t1.display();
    t2.display();
    t3=t1+t2;
    t3.display();
    t3+=t1;
    t3.display();
    result=(t1==t3);
    cout<<result;
    t1=t3=t2;
    t1.display();
    t2.display();
    t3.display();   
    ++t2;
    t2.display();
    return 0;
}

No comments:

Post a Comment