重载++后缀运算符 [英] Overload the ++ postfix operator

查看:109
本文介绍了重载++后缀运算符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

#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

推荐答案

你的代码是正确的:

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.


这篇关于重载++后缀运算符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆