在定义类的成员函数时,经常遇到运算符重载的情况,往往在这时候,不知道应该用友元函数还是成员函数,其实这很好分辨:
运算符的两边各有一个参数,如果在运算符的左边是一个对象的话,那么,成员函数就可以了,例如A*1.2,但是如果这个1.2在运算符的左边,即1.2*A,那么这时候就不能用成员函数了,因为成员函数往往只有一个参数,另一个参数被隐式地传递的调用对象,那么,他返回的也就是一个成员,而1.2仅仅是一个参数,不是对象,这时候就要用友原函数。
#ifndef HEAD4_H_
#define HEAD4_H_
class Time
{
private:
int hours;
int minutes;
public:
Time();
Time(int h,int m);
void AddMin(int m);
void AddHr(int h);
void Reset(int h,int m);
friend Time operator+(const Time &t,const Time &y);
friend Time operator-(const Time &t,const Time &y);
friend Time operator*(double m,const Time &t);
friend Time operator*(const Time &t,double m);
friend std::ostream&operator<<(std::ostream &os,const Time &t);
};
#endif
Time operator*(const Time &t,double m)
{
Time temp;
double total=t.hours*60+t.minutes;
total=total*m;
temp.hours=total/60;
temp.minutes=int(total)%60;
return temp;
}
Time operator*(double m,const Time &t)
{
return t*m;
}
然而,如果此时不是友原函数的话,那么就只有一个参数:
Time Time::operator*(double m)const
{
Time result;
......
return result;
}
另外,非成员函数上不允许使用类型限定符,例如:
Time operator+(const Time &t,const Time &y)const //这个最后的const是不允许的。