所谓运算符重载,即对运算符操作的新定义,减法可以定义成加法,加法可以定义成减法,我想这是核心的含义。
可重载的运算符
+ | - | * | / | % | ^ |
& | | | -= | ! | = | < |
> | += | -= | *= | /= | %= |
^= | &= | |= | << | >> | >>= |
<<= | == | != | <= | >= | && |
|| | ++ | -- | , | ->* | -> |
() | [] | new | delete | new[] | delete[] |
如 C++ Prime Plus 上的一例:
mytime2.h
#ifndef MYTIME2_H_
#define MYTIME2_H_
class Time
{
private:
int hours;
int minutes;
public:
Time();
Time(int h, int m = 0);
void AddMin(int m);
void AddHr(int h);
void Reset(int h = 0, int m = 0);
Time operator+(const Time & t) const;
Time operator-(const Time & t) const;
void operator*(double mult); // 更改了 primer plus 上的例子,测试运算符重载是否需要返回值
void Show() const;
};
#endif
mytime2.cpp
#include <iostream>
#include "mytime2.h"
Time::Time()
{
hours = minutes = 0;
}
Time::Time(int h, int m)
{
hours = h;
minutes = m;
}
void Time::AddMin(int m)
{
minutes += m;
hours += minutes / 60;
minutes %= 60;
}
void Time::AddHr(int h)
{
hours += h;
}
void Time::Reset(int h, int m)
{
hours = h;
minutes = m;
}
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 Time::operator-(const Time & t) const
{
Time diff;
int tot1, tot2;
tot1 = t.minutes + 60 * t.minutes;
tot2 = minutes + 60 * hours;
diff.minutes = (tot2 - tot1) % 60;
diff.hours = (tot2 - tot1) / 60;
return diff;
}
void Time::operator*(double mult)
{
minutes = 60 * hours * mult + minutes * mult;
hours = minutes / 60;
minutes = minutes % 60;
}
void Time::Show() const
{
std::cout << hours << " hours, " << minutes << " minutes";
}
usetime2.cpp
#include <iostream>
#include "mytime2.h"
int main()
{
using std::cout;
using std::endl;
Time weeding(4, 35);
Time waxing(2, 47);
Time total;
Time diff;
Time adjusted(1,1);
cout << "weeding time = ";
weeding.Show();
cout << endl;
cout << "waxing time = ";
waxing.Show();
cout << endl;
cout << "total work time = ";
total = weeding + waxing;
total.Show();
cout << endl;
diff = weeding - waxing;
cout << "weeding time - waxing time = ";
diff.Show();
cout << endl;
adjusted * 1.5;
cout << "adjusted work time = ";
adjusted.Show();
cout << endl;
return 0;
}
结果发现运算符重载的条件还是很开放的,不过也有不允许重载的运算符,如 static_cast 等等,具体请翻看 C++ 资料。
注:运算符重载定义在类内部时,运算的对象默认为左元,也就是说参数只能是被加数,被除数等等,而不能是其他类型。
#ifndef MYTIME2_H_
#define MYTIME2_H_
class Time
{
private:
int hours;
int minutes;
public:
Time operator!(double n, const Time & t); // 错误,const Time & t 必须为左元,且参数只能有一个!!!
};
#endif