重载为类的成员函数:
返回类型 类名::operator 运算符(形参表)
{
函数体
}
重载为类的非成员函数:
返回类型 operator 运算符(形参表)
{
函数体
}
示例:
#include<iostream>
using namespace std;
class Clock //时钟类定义
{
public:
Clock();
Clock(int hour,int minute,int second);
Clock &operator++(); //前置单目运算符重载
Clock operator++(int);//后置单目运算符重载
Clock &operator=(const Clock &c);//=运算符重载
friend ostream &operator<<(ostream &out,const Clock &c);//重载为非成员函数
private:
int hour,minute,second;
};
Clock::Clock(int hour,int minute,int second)
{
if(0<hour&&hour<24&&0<minute&&minute<60&&0<=second&&second<60)
{
this->hour=hour;
this->minute=minute;
this->second=second;
}
else
cout<<"Time error!"<<endl;
}
ostream &operator<<(ostream &out,const Clock &c)
{
out<<c.hour<<":"<<c.minute<<":"<<c.second;
return out;
}
Clock &Clock::operator++()
{
second++;
if(second>=60)
{
second-=60;
minute++;
if(minute>=60)
{
minute-=60;
hour=(hour+1)%24;
}
}
return *this;
}
Clock Clock::operator++(int)
{
Clock old=*this;
++(*this);
return old;
}
Clock &Clock::operator=(const Clock &c2)
{
this->second=c2.second;
this->minute=c2.minute;
this->hour=c2.hour;
return *this;
}
Clock::Clock():hour(0),minute(0),second(0) {}
int main()
{
Clock myClock(23,59,59);
cout<<"First time output:";
cout<<myClock<<endl;
cout<<"show myClock++: ";
cout<<(myClock++)<<endl;
cout<<"show ++ myClock:";
cout<<++myClock<<endl;
Clock newClock;
newClock=myClock;
cout<<"show newClock=myClock:";
cout<<newClock<<endl;
return 0;
}
运行结果: