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.
The final member function should add two objects of type time passed as
arguments.
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, leaving the result in 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
add(time t1,time t2)
{
secs=t1.secs+t2.secs;
if(secs>59)
{ secs - =60; mints++; }
mints+=t1.mints+t2.mints;
if(mints>59)
{ mints - =60; hrs++; }
hrs+=t1.hrs+t2.hrs;
}
void
display( ) const
{ cout
<< hrs << ":" << mints << ":"
<< secs << endl; }
};
/////////////////////////////////////////////////////////////////////////////////////////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.add(time1,time2);
cout << "Time3 is: "; time3.display( );
system("pause");
}
OUTPUT:
0 comments: