本文介绍了重载++后缀运算符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
#include <iostream>
using namespace std;
class Time {
private:
int hours; // 0 to 23
int minutes; // 0 to 59
public:
// required constructors
Time(){
hours = 0;
minutes = 0;
}
Time(int h, int m){
hours = h;
minutes = m;
}
// method to display time
void displayTime() {
cout << "H: " << hours << " M:" << minutes << endl;
}
Time& operator++()
{
++minutes;
if (minutes>=60)
{
++hours;
minutes = minutes - 60;
}
return *this;
}
Time& Time::operator++(int){
Time temp(hours, minutes);
minutes++;
if (minutes >= 60)
{
hours++;
minutes = minutes - 60;
}
return *this;
}
};
int main() {
Time T1(11, 59), T2(10, 40);
T2 = ++(++T1); //
T1.displayTime(); // display 12,01 ok
T2.displayTime(); // display 12,01 ok
T2 = (T1++)++;
T1.displayTime(); // display 12,03 οκ
T2.displayTime(); // display 12,03 why?? i think it must be 12,01
return 0;
}
我的尝试:
问题出在对象T2
What I have tried:
The problem is at the object T2
推荐答案
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.
Time operator++(int)
{
Time temp(hours, minutes);
minutes++;
if (minutes >= 60)
{
hours++;
minutes = minutes - 60;
}
// Return unchanged object here!
return temp;
}
另请参阅 []。
使用后缀实现中的前缀增量:
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;
}
这篇关于重载++后缀运算符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!