有关于c++中操作符重载的问题。

来源:百度知道 编辑:UC知道 时间:2024/04/30 07:52:47
以下一段程序是有关于操作符重载的程序,其中有些语句不甚明白,请有识之士给予解答,谢谢!

1 #include<iostream>
2 #include<stdlib.h>
3 #include<iomanip>
4 using namespace std;
5 class Time
6 {
7 int hour,minute,second;
8 public:
9 void set( int h,int m,int s)
10 {
11 hour=h;
12 minute=m;
13 second=s;
14 }
15 friend Time& operator++(Time& a);
16 friend Time operator++(Time& a,int);
17 friend ostream& operator<<(ostream& o,const Time& t);
18};
19 Time& operator++(Time& a)
20 {
21 if(!(a.second=(a.second+1)%60)&&!(a.minute=(a.minute+1)%60))
22 a.hour=(a.hour+1)%24;
23 return a;
24}
25 Time operator++(Time& a,int)
26{
27 Time t(a);
28 if(!(a.second=(

21、22
21 if(!(a.second=(a.second+1)%60)&&!(a.minute=(a.minute+1)%60))
这句条件的两个表达式是有顺序的C++编译器会
先计算表达式1!(a.second=(a.second+1)%60)的值如果是1值
再计算表达式2!(a.minute=(a.minute+1)%60)的值如果是1值
再计算21行
如果秒加1得不到60了那么表达式1的值为0 也就不会继续计算表达式2和条件里的语句,所以就不会增加分钟和小时的值
实际上可以这样改写代码
if(!(a.second=(a.second+1)%60) && !(a.minute=(a.minute+1)%60) && !(a.hour=(a.hour+1)%24)) ;

27行Time t(a)是拷贝构造函数
因为Time operator++(Time& a,int)表示t++运算,所以需要中间变量保存原值a
35行 只是保持输出重载有返回值而已
也可以写成
return o<<setfill('0')<<setw(2)<<t.hour<<":"<<setw(2)<<t.minute<<":"<<setw(2)<<t.second<<endl<<setfill(' ');