Wednesday 16 August 2017

Add to the time class of Exercise 5 the ability to subtract two time values using the overloaded (-) operator, and to multiply a time value by a number of type float, using the overloaded (*) operator.




SOLUTION:
#include "stdafx.h"
#include "iostream"
using namespace std;
/////////////////////////////////////////////////////////////////////////////////////////
class time
{
            private:
                        int hrs, mints, secs;
            public:
                        time( ) :hrs(0), mints(0), secs(0)        
 { /*Empty Body*/ }
                        time(int h, int m, int s):hrs(h), mints(m), secs(s)
                                     { /*Empty Body*/ }
                        void display( ) const
                        {          
cout << hrs << ":" << mints << ":" << secs << endl; 
}
                        time operator - (time) const;              
time operator * (float) const;
};
//---------------------------------------------------------------------------------------
time time::operator - (time t2) const
{
            int hr, min, sec;
            if(hrs >= t2.hrs)
                        hr = hrs - t2.hrs;
            else
                        hr = t2.hrs - hrs;
            if(mints >= t2.mints)
                        min = mints - t2.mints;
            else
                        min = t2.mints - mints;
            if(min > 59)
            {
                        min -=60;
                        hr++;              
}
            if(secs >= t2.secs)
                        sec = secs - t2.secs;
            else
                        sec = t2.secs - secs;
            if(sec > 59)
            {
                        sec -=60;
                        min++;
            }
            return time(hr, min, sec);       
}


time time::operator * (float num) const
{
            int hr=hrs, min=mints, sec;
            sec=secs*num;
            if(sec > 59)
            {
                        sec -=60;
                        min++;
            }
            if(min > 59)
            {
                        min -=60;
                        hr++;
            }
            return time(hr, min, sec);
}
/////////////////////////////////////////////////////////////////////////////////////////
void main( )
{
            const time time1(10,25,2), time2(5,59,59);
            time time3, time4;
            cout << "Time1 is: ";
                        time1.display( );
            cout << "Time2 is: ";  
                        time2.display( );
            time3 = time1 - time2;
                        cout << "Time3 is: ";  
                                    time3.display( );
            time4 = time1 * 32.14;           
                        cout << "Time4 is = Time1*32.14 = ";           
                                    time4.display( );
            system("pause");
}

OUTPUT:



0 comments: