运算符重载,函数:return type operator + 运算符
- 作为类成员函数重载:Time operator + (Time t)
- 非类成员函数 Time operator+ (Time t1, Time t2)
using namespace std;
class Time {
public:
int hours; // 小时
int minutes; // 分钟
Time() {
hours = 0;
minutes = 0;
}
Time(int h, int m) {
this->hours = h;
this->minutes = m;
}
void show() {
cout << hours << " " << minutes << endl;
}
// write your code here......
Time operator+ (Time t2)
{
int hour = this->hours + t2.hours;
int minute = this->minutes + t2.minutes;
hour += minute / 60;
minute %= 60;
return Time(hour, minute);
}
};
// Time operator+ (Time t1, Time t2) //非成员函数
// {
// int hour = t1.hours + t2.hours;
// int minute = t1.minutes + t2.minutes;
// hour += minute / 60;
// minute %= 60;
// return Time(hour, minute);
// }
int main() {
int h, m;
cin >> h;
cin >> m;
Time t1(h, m);
Time t2(2, 20);
Time t3 = t1 + t2;
t3.show();
return 0;
}