In: Computer Science
Q3 Develop a Time class which encapsulates hour ,minute
and second data members. Provide overloaded +, -, ++ and - -
overloaded operators for Time.
I have given the program below. I hope it will help you, if you have any query then tell me.
Take care
Programs:
#include <iostream>
#include <math.h>
using namespace std;
class Time
{
private:
int second;
int minute;
int hour;
public:
//Paramiterised Constructor
Time(int h, int m, int s=0) {
second = s;
minute = m;
hour = h;
}
//Default Constructor
Time (){
second = 0;
minute = 0;
hour = 0;
}
//Notice nothing inside barcket which indicates pre-increment ++.
Time operator ++ ()
{
Time temp;
//as in the given question for the test data there is no "second" value I am incrementing "minute" as functionality of ++. If wanted same can be done to increment second value also
temp.minute = ++minute;
temp.hour = hour;
if(minute == 60){
minute = 0;
temp.minute = 0;
hour = hour + 1;
temp.hour = temp.hour + 1;
}
return temp;
}
// Notice int inside barcket which indicates post-increment ++ .
Time operator ++ (int)
{
Time temp;
temp.minute = minute++;
temp.hour = hour;
if(minute == 60){
minute = 0;
hour = hour + 1;
}
return temp;
}
// Method to set variables of Time
void setvalue(int h, int m, int s=0) {
second= s;
minute = m;
hour = h;
}
// Method to get Time
Time getvalue(){
Time temp;
temp.hour=hour;
temp.minute=minute;
temp.second=second;
return temp;
}
// Method to print Time
void printvalue()
{ cout << "\n Time = "<< hour << " H " << minute <<" M " <<second << " S " <<"\n"; }
};
//main function
int main()
{
Time T1(11,59), T2(10,40);
cout<< "value of T1";
T1.printvalue();
cout<< "value of T2";
T2.printvalue();
// Operator function is called, only then value of obj is assigned to obj1
Time T3 = ++T1;
cout<< "value of T1 after operator function";
T1.printvalue();
cout<< "value of T3, ie. assigned value of T1 at pre-increment";
T3.printvalue();
// Assigns value of obj to obj1, only then operator function is called.
Time T4 = T2++;
cout<< "value of T2 after operator function";
T2.printvalue();
cout<< "value of T4, ie. assigned value of T2 at post-increment ";
T4.printvalue();
return 0;
}