通过运用友元函数的形式重载运算符++
#include <iostream>
using namespace std;
class Time{
int hour ;
int min;
int sec;
public:
void display();
friend Time operator++(Time &t);
Time(int h,int m,int s):hour(h),min(m),sec(s){};
};
void Time::display(){
cout<<hour<<":"<<min<<":"<<sec<<endl;
}
Time operator++(Time &t){
++t.sec;
if(t.sec>=60){
t.sec=0;
++t.min;
if(t.min>=60){
t.min=0;
++t.hour;
if(t.hour>=24)
t.hour=0;
}
}
return t;
}
int main(){
Time t1(23,59,59);
t1.display();
++t1;
t1.display();
operator++(t1);
t1.display();
return 0;
}
当需要将重载函数定义为类的成员函数的时候
#include <iostream>
using namespace std;
class Time{
int hour ;
int min;
int sec;
public:
void display();
Time operator++();
Time(int h,int m,int s):hour(h),min(m),sec(s){};
};
void Time::display(){
cout<<hour<<":"<<min<<":"<<sec<<endl;
}
Time Time::operator++(){
++sec;
if(sec>=60){
sec=0;
++min;
if(min>=60){
min=0;
++hour;
if(hour>=24)
hour=0;
}
}
return *this;
}
int main(){
Time t1(23,59,59);
t1.display();
++t1;
t1.display();
t1.operator++();
t1.display();
return 0;
}
![](https://img-my.csdn.net/uploads/201301/09/1357724679_5722.png)