Write a C++ program to implement time class that has separate data members for hours, minutes and seconds. Overload + Operator to add two times (object) and -- operator to decrement the time by one second.
#include <iostream>
using namespace std;
class Time{
int hours, minutes, seconds;
public:
Time(){}
Time(int h, int m, int s){
hours = h;
minutes = m;
seconds = s;
}
void display(){
cout<<this->hours<<":"<<this->minutes<<":"<<this->seconds<<endl;
}
Time operator+(const Time &a){
int h, m, s;
h = this->hours + a.hours;
m = this->minutes + a.minutes;
s = this->seconds + a.seconds;
if(s >= 60){
s -= 60;
m++;
}
if(m >= 60){
m -= 60;
h++;
}
return Time(h, m, s);
}
Time operator--(){
return *this + Time(0, 0, -1);
}
};
int main(){
int arr[3];
Time time[2];
string times[] = {"Hours", "Minutes", "Seconds"};
for(int i = 0; i < 2; i++){
cout<<"Enter time "<<i + 1<<" details\n";
for(int j = 0; j < 3; j++){
cout<<times[j]<<": ";
cin>>arr[j];
}
time[i] = Time(arr[0], arr[1], arr[2]);
}
cout<<"Time 1 + Time 2\n"; (time[0] + time[1]).display();
cout<<"--Time 1\n"; (--time[0]).display();
cout<<"--Time 2\n"; (--time[1]).display();
return 0;
}
Comments
Leave a comment