①将其原型放在类声明中,并在原型声明前加上关键字friend
虽然是在类中声明的,但是他却不是成员函数,不能通过成员运算符来调用;
虽然他不是成员函数,但是和成员函数的权限相同
②编写函数定义,因为他不是成员函数,所以函数定义不能加 (类名:: ) 限定符,在定义中也不需要用关键字friend
例子
friend TIME operator*(double b, const TIME & t);
#ifndef __TIME_H__
#define __TIME_H__
class TIME
{
private:
int nHours;
int nMinutes;
public:
TIME();
TIME(int H, int M);
void SetTime(int H, int M);
void ShowTime(void) const;
TIME operator+(const TIME & t) const;
TIME operator*( double b) const;
friend TIME operator*(double b, const TIME & t);
};
#endif
再此过程中 发现了 非成员函数不能用const 修饰符来修饰
TIME operator(double b, const TIME & t) const 是错误的*
TIME operator*(double b, const TIME & t)
{
TIME Result;
long TotalMinutes = t.nHours * b * 60 + t.nMinutes * b;
Result.nHours = TotalMinutes/60;
Result.nMinutes = TotalMinutes%60;
return Result;
}
#include "Time.h"
int main(int argc, char* argv[])
{
TIME a(1,50);
TIME b(2,10);
TIME c = 10.3 * a ;
c.ShowTime();
return 0;
}