【发布时间】:2018-09-25 22:28:39
【问题描述】:
我正在尝试实现一个时间类,它设置时间、打印它并增加一秒。我想通过重载 ++ 运算符来实现它,它工作正常,但只有当我在参数列表中定义一个参数时。如何在不定义任何参数的情况下使其工作,因为我知道它会将当前时间增加一秒并且我不需要任何参数?
#include <iostream>
using namespace std;
class time
{
int h,m,s;
public:
time(int a, int b, int c);
void printtime();
time& operator++(int);
};
[...]
time& time::operator++(int x)
{
s++;
if (s>59) {
m++;
s -= 60;
if (m>59) {
h++;
m -= 60;
if (h>23) {
h = m = s = 0;
}
}
}
return *this;
}
int main()
{
try {
time now(22,58,59);
now.printtime();
now++;
now.printtime();
}
catch(const char* u) {
cout << u << endl;
}
return 0;
}
另外,我将需要实现后缀运算符,这会增加时间,但仅在打印旧时间之后,以便
time now(2,23,59);
(now++).printtime();
将打印 2:23:59,但之后 now 的值将是 3,0,0。如何实现前缀和后缀 ++ 运算符并在主函数中调用它们时有所作为?
【问题讨论】:
标签: c++ operator-overloading post-increment pre-increment