C++ program to overload Binary Minus (-) operator

//to evaluate the expression A=2-B where A and B are objects of a class

#include <iostream>
using namespace std;
class Time
{
    private:
        int h,m,s;
    public:
        Time()
        {
            h=m=s=0;
        }
        Time(int hr,int min,int sec)
        {
            h=hr;
            m=min;
            s=sec;
        }
        void show()
        {
            cout<<h<<"hour "<<m<<"minute "<<s<<"second."<<endl;
        }
        friend Time operator-(int,Time);
};
Time operator-(int n,Time t)
{
    Time tt;
    tt.h=n-t.h;
    tt.m=n-t.m;
    tt.s=n-t.s;
    return tt;
}
int main()
{
    Time B(5,32,45),A;
    B.show();
    A=2-B;
//same as operator-(2,B)
    A.show();
    return 0;
}

No comments:

Post a Comment