作者:jicanmeng
时间:2014年11月17日
本文完全来自于learncpp.com,作者已经写的极其简单明了,我觉得不能写的更好了。只摘抄了一部分,如下:
1. operators in C++ are implemented as functions.
2. Almost any operator in C++ can be overloaded. The exceptions are: arithmetic if (?:), sizeof, scope (::), member selector (.), and member pointer selector (.*).
重载运算符时,需要注意的几个地方是:
First, at least one of the operands in any overloaded operator must be a user-defined type. This means you can not overload the plus operator to work with one integer and one double. However, you could overload the plus operator to work with an integer and a Mystring.
Second, you can only overload the operators that exist. You can not create new operators. For example, you could not create an operator ** to do exponents.
Third, all operators keep their current precedence and associativity, regardless of what they're used for.
上面提到,运算符重载是通过函数来实现的。是通过什么函数呢?如果重载的运算符是+,那么函数名为operator+。learncpp.com上面是这么说的:
When you see the expression nX + nY, you can translate this in your head to operator+(nX, nY) (where operator+ is the name of the function). Similarly dX + dY becomes operator+(dX, dY).