单目运算符重载
前置自加运算符重载Time类
#include <iostream>
using namespace std;
class Time
{
public:
Time(){minute=0;sec=0;}//默认构造函数
Time(int m,int s):minute(m),sec(s){}//构造函数重载
Time operator++();//声明运算符重载函数
void display(){cout<<minute<<":"<<sec<<endl;}//输出时间
private:
int minute;
int sec;
};
//定义运算符重载函数
Time Time::operator++()
{
if(++sec>=60)
{
sec-=60; //满60秒进1分钟
++minute;
}
return *this; //返回当前对象值
}
int main()
{
Time time1(34,0);
++time1;
time1.display();
return 0;
}
后置自加运算符重载Time类
#include <iostream>
using namespace std;
class Time
{
public:
Time(){minute=0;sec=0;}//默认构造函数
Time(int m,int s):minute(m),sec(s){}//构造函数重载
Time operator++();//声明运算符重载函数
Time operator++(int);
void display(){cout<<minute<<":"<<sec<<endl;}//输出时间
private:
int minute;
int sec;
};
//定义运算符重载函数
Time Time::operator++()
{
if(++sec>=60)
{
sec-=60; //满60秒进1分钟
++minute;
}
return *this; //返回当前对象值
}
Time Time::operator++(int)
{
Time temp(*this);
sec++;
if(sec>=60)
{
sec-=60;
++minute;
}
return temp;
}
int main()
{
Time time1(34,59),time2;
cout<<"time1:";
time1.display();
++time1;
cout<<"++time1:";
time1.display();
time2=time1++;
cout<<"time1++:";
time1.display();
cout<<"time2:";
time2.display();
return 0;
}