一个C++的操作符重载问题,帮忙解释下

来源:百度知道 编辑:UC知道 时间:2024/05/24 01:09:19
#include "stdafx.h"
#include <iostream>
#include <iomanip>
using namespace std;

class Time{
int hour,minute,second;
public:
void set(int h,int m,int s){hour=h,minute=m,second=s;}
friend Time& operator++(Time& a);
friend Time& operator++(Time& a,int );
friend ostream& operator<<(ostream& o,const Time& t);
};

Time& operator++ (Time& a){
if (!(a.second=(a.second+1)%60)&&!(a.minute=(a.minute+1)%60))
a.hour=(a.hour+1)%24;
return a;

}

Time& operator++(Time& a,int){
Time t(a);
if(!(a.second=(a.second+1)%60)&&!(a.minute=(a.minute+1)%60))
a.hour=(a.hour+1)%24;
return t;
}

ostream& operator<<(ostream& o,const Time& t){
o<<setfill('0')<<setw(2)<<t.hour<<":"<<setw(2)<<t.minute<<":";
return o<<setw(2)&

Time& operator++(Time& a,int);
这个函数的返回值类型应当是Time的对象,而不是引用。因为变量a的生存周期只在冲在函数++内部有效,当++推出的时候会自动收回a的空间,之后对a的引用也全都无效了,所以会发生错误。
Time operator++(Time& a,int);