请教关于运算符重载的问题
//-----------------------------
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 a;
}
//----------------------------------
ostream & operator < <(ostream & o,const Time & t){
o < <setfill( '0 ') < <setw(2) < <t.hour < < ": " < <setw(2) < <t.minute < < ": ";
return o < <setw(2) < <t.second < < "\n " < <setfill( ' ');
}
//----------------------------------
int main(){
Time t;
t.set(11,59,58);
cout < <t++;
cout < <++t;
}
///以上是代码////////////////////////////////////////////////
请问friend Time & operator++(Time & a);
friend Time operator++(Time & a,int);中的& operator和operator有什么区别,还有为什么一个后面还有个int
[解决办法]
friend Time & operator++(Time & a);
------------------------------------
friend,友元
Time &,返回Time类型的引用
operator++,重载++
friend Time operator++(Time & a,int);
----------------------------------------
这个和上面两个区别。
1,没有了&
2,多了个int参数。
第一,为什么多了int呢?
因为++有前++,和后++之分。
比如:
int b = 5;
b++;
++b;
这俩是有区别的。所以,加了个int以区别一个是前加加,一个是后加加。
另外一个区别,&之有无,还在这里。
返回值。
前加加直接返回b。返回自身的引用。
后加加,因为用完之后才加,所以,定义1临时变量temp,temp = b; b= b+1; returm temp;
所以,返回的是temp。所以没有引用。
明白了否?
[解决办法]
模拟一下++的行为:
// 前缀形式:
int& int::operator++()
{
*this += 1; // 增加
return *this; // 取回值
}
//后缀形式:
const int int::operator++(int)
{
int oldValue = *this; // 取回值
++(*this); // 增加
return oldValue; // 返回被取回的值
}
//以上纯粹是示范一下++的行为.
//可以看到前缀和后缀返回值类型的区别.