Add given timestamps by overloading + operator in C++ Time Class
Last Updated :
30 Aug, 2021
- In C++, we can make operators to work for user-defined classes. This means C++ has the ability to provide the operators with a special meaning for a data type, this ability is known as operator overloading.
- In this article, we will overload an operator ‘+’ in the Time class so that we can concatenate two timestamps by just using +.
Example:
Input: T1 = 5:50:30, T2 = 7:20:34
Output: 13:11:4
Approach: To achieve the + operator overloading, below steps/functions are made:
Class Time is defined in which there are 3 variables to store the value of hours, minutes and seconds respectively.
int HR, MIN, SEC;
where HR is for hours,
MIN is for minutes, and
SEC is for seconds
- setTime() function to set values of HR, MIN and SEC.
void setTime(int x, int y, int z)
{
x = HR;
y = MIN;
z = SEC;
}
- showTime() function to display the time in a specific format (HH:MM:SS).
void showTime()
{
cout << HR << ":" << MIN << ":" << SEC;
}
- normalize() function to convert the resultant time into standard form.
Overloading of + operator to add time T1 and T2 using operator overloading.
Below is the C++ program implementing + overloading to add two timestamps:
C++
#include <iostream>
using namespace std;
class Time {
private :
int HR, MIN, SEC;
public :
void setTime( int x, int y, int z)
{
HR = x;
MIN = y;
SEC = z;
}
void showTime()
{
cout << endl
<< HR << ":" << MIN << ":" << SEC;
}
void normalize()
{
MIN = MIN + SEC / 60;
SEC = SEC % 60;
HR = HR + MIN / 60;
MIN = MIN % 60;
}
Time operator+(Time t)
{
Time temp;
temp.SEC = SEC + t.SEC;
temp.MIN = MIN + t.MIN;
temp.HR = HR + t.HR;
temp.normalize();
return (temp);
}
};
int main()
{
Time t1, t2, t3;
t1.setTime(5, 50, 30);
t2.setTime(7, 20, 34);
t3 = t1 + t2;
t1.showTime();
t2.showTime();
t3.showTime();
return 0;
}
|
Output:
5:50:30
7:20:34
13:11:4
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...