不传递参数重载运算符
Overloading operator without passing argument
我正在尝试实现一个时间 class,它设置时间、打印它并增加一秒。我想通过重载 ++ 运算符来实现它,它工作正常,但只有当我在参数列表中定义一个参数时。我怎样才能在不定义任何参数的情况下使其工作,因为我知道它会将当前时间增加一秒并且我不需要任何参数?
#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。如何同时实现前缀和后缀 ++ 运算符并在主函数中调用它们时有所不同?
问题是有两个运算符叫做 ++。一种是预增量,一种是 post-增量。
为了区分它们,C++ 的创建者决定 post 增量版本采用 "int" 参数。不用,但必须要有,否则就是预自增运算符
如果要去掉参数,可以这样使用:
++now;
此外,post-增量版本确实需要 return 结构的 COPY,其状态与增量之前一样。这是 pre- 和 post- 运算符之间的主要区别。实现 pre 运算符要简单得多,所以如果这就是您所需要的,那就是您应该使用的。
为了完整起见,这里是运算符以及它们应该如何为 class T:
编写
T& T::operator++(); [pre-increment]
T& T::operator--(); [pre-decrement]
T T::operator++(int); [post-increment]
T T::operator--(int); [post-decrement]
请注意,前版本 return 是对对象的引用,而 post- 版本 return 是副本(不是引用)。该副本应包含 increment/decrement.
之前的值
我正在尝试实现一个时间 class,它设置时间、打印它并增加一秒。我想通过重载 ++ 运算符来实现它,它工作正常,但只有当我在参数列表中定义一个参数时。我怎样才能在不定义任何参数的情况下使其工作,因为我知道它会将当前时间增加一秒并且我不需要任何参数?
#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。如何同时实现前缀和后缀 ++ 运算符并在主函数中调用它们时有所不同?
问题是有两个运算符叫做 ++。一种是预增量,一种是 post-增量。
为了区分它们,C++ 的创建者决定 post 增量版本采用 "int" 参数。不用,但必须要有,否则就是预自增运算符
如果要去掉参数,可以这样使用:
++now;
此外,post-增量版本确实需要 return 结构的 COPY,其状态与增量之前一样。这是 pre- 和 post- 运算符之间的主要区别。实现 pre 运算符要简单得多,所以如果这就是您所需要的,那就是您应该使用的。
为了完整起见,这里是运算符以及它们应该如何为 class T:
编写T& T::operator++(); [pre-increment]
T& T::operator--(); [pre-decrement]
T T::operator++(int); [post-increment]
T T::operator--(int); [post-decrement]
请注意,前版本 return 是对对象的引用,而 post- 版本 return 是副本(不是引用)。该副本应包含 increment/decrement.
之前的值