Wednesday 16 August 2017

Create a class called time that has separate int member data for hours, minutes, and seconds. One constructor should initialize this data to 0, and another should initialize it to fixed values. Another member function should display it, in 11:59:59 format. Instead of a function add_time() it uses the overloaded + operator to add two times. A main() program should create two initialized time objects (should they be const ?) and one that isn’t initialized. Then it should add the two initialized values together, returning the result to the third time variable. Finally it should display the value of this third variable.Make appropriate member functions const.



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 time::operator + (time t2) const
{
            int sec, min, hr;
            hr = hrs + t2.hrs;
            min = mints + t2.mints;
            if(min > 59)
                        {           min -=60;         hr++;               }
            sec=secs + t2.secs;
            if(sec > 59)
                        {           sec -=60;         min++;             }
            return time(hr, min, sec);       
}
/////////////////////////////////////////////////////////////////////////////////////////
void main( )
{
            const time time1(10,25,2),time2(5,59,59);                 time time3;
            cout << "Time1 is: ";               time1.display( );
            cout << "Time2 is: ";               time2.display( );
            time3 = time1 + time2;
            cout << "Time3 is: ";               time3.display( );
            system("pause");
}
OUTPUT:
 

0 comments: