运算符重载包括重载为类的成员函数和重载为友元函数。
这里要特别注意的就是单目运算符的前置、后置时的运算符重载规则。
下面是简单的说明性代码,++,--(前置和后置)重载为类的成员函数和类的友元函数时的情形
#include<iostream>
using namespace std;
class Time
{
public:
Time(int h=0,int m=0)
{
H=h;
M=m;
}
void showtime();
Time operator ++();//前置运算符++(类的成员函数)
Time operator ++(int);//后置运算符++(类的成员函数)
friend Time operator --(Time & oper);//重载为类的友元函数
friend Time operator --(Time & oper,int);///重载为类的友元函数
private:
int H,M;
};
void Time::showtime()
{
cout<<"hour="<<H<<"minute="<<M<<endl;
}
Time Time::operator++()
{
M++;
H++;
return *this;//返回当前的操作对象
}
Time Time::operator++(int)
{
//Time old=*this;
//++(*this);
//return old;
return Time(H++,M++);//创建临时我一个无名对象作为返回值
}
Time operator --(Time & oper)
{
return Time(--oper.H,--oper.M);
}
Time operator --(Time & oper,int)
{
return Time(oper.H--,oper.M--);
}
int main()
{
Time t1(10,22);
t1.showtime();
cout<<"------------------运算符重载为类的成员函数---------------"<<endl;
cout<<"使用前置运算符的++"<<endl;
(++t1).showtime();
t1.showtime();
cout<<"使用后置运算符的++"<<endl;
(t1++).showtime();
t1.showtime();
cout<<"----------------------------------------------------------"<<endl;
cout<<"------------------运算符重载为类的友元函数---------------"<<endl;
cout<<"使用前置运算符--"<<endl;
(--t1).showtime();
t1.showtime();
cout<<"使用后置运算符"<<endl;
(t1--).showtime();
t1.showtime();
return 0;
}