- 2074 Chaitra · 7 marks
Time class: +, <= and << overloading
Short answer
Overload + as member: add seconds, carry to minutes, carry to hours, return new Time. Overload <= as member: convert both to total seconds and compare. Overload << as friend: print formatted like "2h 45m 50s".
Write operator functions as member function of a class to overload arithmetic operator +, logical operator '<=' and stream operator '<<' to operate on the objects of user defined type time (hr, min, sec).
Three operators are overloaded for class Time:
+adds two times (arithmetic, member function).<=compares two times (logical, member function).<<prints a time. Its left operand iscout, anostreamobject, so it cannot be a member ofTime(it could only be a member ofostream, which we cannot modify). It is therefore written as a friend (non-member) function.
#include <iostream>
using namespace std;
class Time {
int hr, min, sec;
public:
Time(int h = 0, int m = 0, int s = 0) { hr = h; min = m; sec = s; }
// arithmetic + : adds two times
Time operator+(Time t) {
Time r;
r.sec = sec + t.sec;
r.min = min + t.min + r.sec / 60;
r.sec = r.sec % 60;
r.hr = hr + t.hr + r.min / 60;
r.min = r.min % 60;
return r;
}
// logical <= : true if this time is less than or equal to t
bool operator<=(Time t) {
int a = hr * 3600 + min * 60 + sec;
int b = t.hr * 3600 + t.min * 60 + t.sec;
return a <= b;
}
// stream insertion operator
friend ostream& operator<<(ostream &out, Time &t) {
out << t.hr << "h " << t.min << "m " << t.sec << "s";
return out;
}
};
int main() {
Time t1(2, 45, 50), t2(1, 20, 30), t3;
t3 = t1 + t2;
cout << "t1 = " << t1 << endl;
cout << "t2 = " << t2 << endl;
cout << "t1 + t2 = " << t3 << endl;
if (t1 <= t2) cout << "t1 <= t2" << endl;
else cout << "t1 > t2" << endl;
return 0;
}
Output:
t1 = 2h 45m 50s
t2 = 1h 20m 30s
t1 + t2 = 4h 6m 20s
t1 > t2
Seconds 50 + 30 = 80 gives 1 min carry and 20 s; minutes 45 + 20 + 1 = 66 gives 1 hr carry and 6 min; hours 2 + 1 + 1 = 4.
✓ Answer checked by Claude Opus 5.5 (high effort)
Related questions
- City class with operator overloading · Object Oriented Programming, chapter 5
- Overload index operator [] for array class · Object Oriented Programming, chapter 5
- Binary operator member function one argument · Object Oriented Programming, chapter 5
- Overloading via member and non-member function · Object Oriented Programming, chapter 5
- Time class: add two objects · Object Oriented Programming, chapter 1
- Member function as friend of another class · Object Oriented Programming, chapter 4
- Significance of user defined functions · Computer Programming, chapter 6
- Switch versus user defined function · Computer Programming, chapter 5
- Arithmetic versus logical IF · Computer Programming, chapter 11 · asked 3×
- How a function is defined in C · Computer Programming, chapter 6