算术运算符
你可以重载所有基本算术运算符:
+和+=-和-=*和*=/和/=&和&=|和|=^和^=>>和>>=<<和<<=
所有运算符的重载都是一样的。向下滚动以获得解释
在 class / struct 之外超载:
//operator+ should be implemented in terms of operator+=
T operator+(T lhs, const T& rhs)
{
lhs += rhs;
return lhs;
}
T& operator+=(T& lhs, const T& rhs)
{
//Perform addition
return lhs;
}
class / struct 内部超载:
//operator+ should be implemented in terms of operator+=
T operator+(const T& rhs)
{
*this += rhs;
return *this;
}
T& operator+=(const T& rhs)
{
//Perform addition
return *this;
}
注意:operator+应该返回非 const 值,因为返回引用没有意义(它返回一个新对象)也不会返回 const 值(通常你不应该通过 const 返回)。第一个参数是按值传递的,为什么?因为
- 你无法修改原始对象(
Object foobar = foo + bar;毕竟不应该修改foo,这没有意义) - 你不能把它变成
const,因为你必须能够修改对象(因为operator+是用operator+=实现的,它修改了对象)
传递 const& 将是一个选项,但是你必须制作传递对象的临时副本。通过传递值,编译器会为你完成。
operator+= 返回对自身的引用,因为它可以链接它们(不要使用相同的变量,由于序列点,这将是未定义的行为)。
第一个参数是一个引用(我们想要修改它),但不是 const,因为那时你将无法修改它。第二个参数不应该被修改,因此性能原因是由 const& 传递的(通过 const 引用传递比按值更快)。