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.
#include<iostream>
#include <iomanip>
using namespace std;
class Time {
private:
int hours;
int minutes;
int seconds;
public:
Time(){ // default constructor
hours = 0;
minutes = 0;
seconds = 0;
}
Time(int h, int m, int s) { // parameterized constructor
hours = h;
minutes = m;
seconds = s;
}
void display(){
cout << setw(2)<<setfill('0')<< hours
<< ":" << setw(2)<<setfill('0')<< minutes
<< ":" << setw(2)<<setfill('0')<< seconds << endl;
}
void add(Time x, Time y) {
int tmp=0;
seconds = x.seconds + y.seconds;
if(seconds > 59){
seconds = seconds-60;
tmp++;
}
minutes = x.minutes + y.minutes+tmp;
tmp=0;
if(minutes > 59){
minutes-=60;
tmp++;
}
hours = x.hours + y.hours+tmp;
if(hours >= 24)
hours-=24;
}
};
int main() {
Time time1(5, 6, 58);
Time time2(7, 58, 3);
Time time3(0, 0, 0);
cout<<"Time_1 ";
time1.display();
cout<<"Time_2 ";
time2.display();
cout<<"Time_3 ADD Time 1 and Time 2: ";
time3.add(time1, time2);
time3.display();
return 0;
}
Comments
Leave a comment