1.什么是运算符重载
运算符重载是一种函数重载。
运算符函数的格式:
operatorop(argument-list)例如,operator+()重载+运算符。其中的op,必须是有效的C++运算符,如operator@()会报错,因为C++中没有@运算符。2.重载运算符的使用
如下例所示:
class Test{public:Test operator+(Test &test);}
调用运算符函数的方式有两种:
Test t1;Test t2;1)普通函数调用Test t3 = t1.operator+(t2);2)运算符方式调用,实质上是调用的1)中的operator+()函数Test t3 = t1+t2;3.运算符重载示例
示例代码如下,+运算符重载,计算时分相加。mytest.h
#pragma onceclass Time{private: int hours; int minutes;public: Time(); Time(int h,int m=0); Time operator+(const Time&t) const; void Show() const;};
mytest.cpp
#include "mytest.h"#includeTime::Time(){ hours=minutes=0;}Time::Time(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;}void Time::Show() const{ std::cout< <<" hours, "< <<" minutes"<
test.cpp
#include "mytest.h"#includeint main(){ Time planning; Time coding(2,40); Time fixing(5,55); Time total; total = coding+fixing; std::cout<<"coding+fixing = "; total.Show(); total = coding.operator+(fixing); std::cout<<"coding.operator+(fixing) = "; total.Show(); total = coding+fixing+coding; std::cout<<"coding.operator+(fixing) = "; total.Show(); return 0;}
输出结果:
4.运算符重载的注意事项:
1)重载的运算符必须是有效的C++运算符2)运算符操作数至少有一个是用户定义类型这是为了防止重载标准类型的运算符如将减法运算符(-)重载为计算两个double的和,而不是差,是不被允许的。3)不能违反运算符原有的规则如求模运算符(%),必须要有两个操作数。4)部分运算符不允许重载如:sizeof,::,:等
参考资料:《C++ Primer.Plus》 pp.381-390