【问题标题】:Overloading operator without passing argument重载运算符而不传递参数
【发布时间】: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


    【解决方案1】:

    问题是有两个运算符叫 ++。一个是前置增量,一个是后置​​增量。

    为了区分它们,C++ 的创建者决定后增量版本将采用“int”参数。没用过,但必须有,否则就是前置自增运算符。

    如果要去掉参数,可以这样使用:

    ++now;
    

    此外,后增量版本确实需要返回结构的副本,其状态与增量之前的状态相同。这是前置运算符和后置运算符之间的主要区别。实现 pre 运算符要简单得多,所以如果这就是你所需要的,那就是你应该使用的。

    为了完整起见,这里是运算符以及应如何为类 T 编写它们:

    T& T::operator++();   [pre-increment]
    T& T::operator--();   [pre-decrement]
    T T::operator++(int); [post-increment]
    T T::operator--(int); [post-decrement]
    

    请注意,pre-version 返回对对象的引用,而 post-version 返回一个副本(不是引用)。该副本应包含增量/减量之前的值。

    【讨论】:

    • 你也可以提到后缀版本不应该返回引用,只有前缀版本会。
    • @papagaga 是的,我正在编辑你的评论。
    • 是的,我已经从您的评论中知道了,但谢谢。这正是我实现它的方式,并且运行良好。 :) 非常感谢!
    猜你喜欢
    • 1970-01-01
    • 2015-12-21
    • 1970-01-01
    • 2014-07-24
    • 1970-01-01
    • 1970-01-01
    • 2013-07-13
    • 1970-01-01
    • 2015-08-22
    相关资源
    最近更新 更多