C++中的操作符重载

class Time
{
private:
int hours;
int minutes;
public:
Time(int h = 0, int m = 0);
};

1、二元操作符的两个参数均为Time类对象：

Time Time::operator +(const Time &t) const
{
Time sum;
sum.minutes = minutes + t.minutes;
sum.hours = hours + t.hours + sum.minutes/60;
sum.minutes %= 60;
return sum;
}

Time operator+(const Time &t1, const Time &t2)
{
Time sum;
sum.minutes = t1.minutes + t2.minutes;
sum.hours = t1.hours + t2.hours + sum.minutes/60;
sum.minutes %= 60;
return sum;
}

class Time
{
private:
int hours;
int minutes;
public:
Time(int h = 0, int m = 0);
Time operator+ (const Time & t)const;
//friend Time operator+ (const Time & t1, const Time & t2);
};

Time coding(2,40);
Time fixing(5,55);
Time total;
total = coding + fixing;

2、二元操作符的一个参数为Time类对象：

Time operator+ (double n)const;

Time Time::operator+(double n) const
{
Time result;
int i = n;
n = n - i;

result.minutes = minutes + n * 60;
result.hours = hours + i + result.minutes /60;
result.minutes %= 60;

return result;
}

friend Time operator+ (double n, const Time & t);

Time operator+ (double n, const Time & t)
{
Time result;
int i = n;
n = n - i;

result.minutes = t.minutes + n * 60;
result.hours = t.hours + i + result.minutes /60;
result.minutes %= 60;

return result;
}

Time operator+ (double n, const Time & t)
{
return t * n;
}

3、综合使用：

int a = 3.33;

Time (double dhrs);

Time::Time(double dhrs)
{
int i = dhrs;
dhrs= dhrs - i;

hours = i;
minutes = dhrs * 60;
}

Time planning；
planning = 1.5;

notes：

explicit Time (double dhrs);

friend Time operator+ (const Time & t1, const Time & t2);

Time operator+ (const Time & t1, const Time & t2)
{
Time sum;
sum.minutes = t1.minutes + t2.minutes;
sum.hours = t1.hours + t2.hours + sum.minutes/60;
sum.minutes %= 60;
return sum;
}

Time A, B;
A + B;
A + 1.5；
1.5 + A；