重载运算符(时间类友元)

#include
using namespace std;
class Time
{
private:
int hour;
int minute;
int second;
public:
Time(int a=0,int b=0,int c=0)
{
this->hour=a;
this->minute=b;
this->second=c;
}
void Show()
{
cout<<hour<<":"<<minute<<":"<<second<<endl;
}
friend Time operator ++(Time &y);//这里定义了这个是Time类的所以在后面再出现的时候也要声明它的类型
friend Time operator ++(Time &y,int);//这里的int 是因为++就是x=x+1的意思所以要int是给1的
} ;
Time operator ++(Time &y)//记住他是time类的并且是Time类中的函数 所以要Time Time ::
{
Time x;
y.second++;
x.second=y.second;
x.hour=y.hour;
x.minute=y.minute;
return x;//这里不要忘了返回值 否则就白运算了
}
Time operator ++(Time &y,int)//同上
{
Time x;
x.second=y.second;
x.hour=y.hour;
x.minute=y.minute;
y.second++;
return x;//这里不要忘了返回值 否则就白运算了
}

int main()
{
Time t1(10,25,52),t2,t3;//定义一个时间对象t1,带参数,t2、t3对象不带参数
t1.Show();
t2=++t1;//使用重载运算符++完成前置++
t1.Show();
t2.Show();
t3=t1++;//使用重载运算符++完成后置++
t3.Show();
t1.Show();
return 0;
}

原文地址:https://www.cnblogs.com/hzshisan/p/12571120.html