且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

重载++后缀运算符

更新时间:2023-02-20 23:20:30

你的代码是正确的:

It is correct by your code:
T2 = ++(++T1);



1.你在括号中增加T1

2.你增加大括号外的T1

3.你 T1值分配给T2



提示:使用调试器步骤进入此代码行的三个函数调用。


1. you increment the T1 in the braces
2. you increment the T1 outside the braces
3. you assign the T1 values to T2

tip: use a debugger to step into the three function calls of this code line.


后缀运算符的实现是错误的。您必须返回 temp (未更改的对象)而不是修改的对象:

Your implementation of the postfix operator is wrong. You must return temp (the unchanged object) instead of the modified object:
Time operator++(int)
{
    Time temp(hours, minutes);
    minutes++;
    if (minutes >= 60)
    {
        hours++;
        minutes = minutes - 60;
    }
    // Return unchanged object here!
    return temp;
}



另请参阅增量和递减运算符重载(C ++) [ ^ ]。

使用后缀实现中的前缀增量:


See also Increment and Decrement Operator Overloading (C++)[^].
That uses the prefix increment within the postfix implementation:

Time operator++(int)
{
    Time temp = *this;
    *++this;
    return temp;
}


由于您要覆盖两个运算符,因此不适用正常的排序规则。在将结果传递到左侧之前,将完全评估每个表达式的右侧。使用调试器逐步执行代码将显示发生的情况。
Since you are overriding both operators the normal ordering rules do not apply. The right-hand side of each expression will be completely evaluated before the result is passed to the left-hand side. Stepping through the code with your debugger will show you what happens.