是否有规范或推荐的模式用于在 C++ 类数字类中实现算术运算符重载?
在 C++ FAQ 中,我们有一个异常安全的赋值运算符,可以避免大多数问题:
class NumberImpl;
class Number {
NumberImpl *Impl;
...
};
Number& Number::operator=(const Number &rhs)
{
NumberImpl* tmp = new NumberImpl(*rhs.Impl);
delete Impl;
Impl = tmp;
return *this;
}
但是对于其他运算符(+、+= 等),除了让它们表现得像内置类型上的运算符外,几乎没有给出什么建议。
有定义这些的标准方法吗?这就是我想出的 - 有没有我没有看到的陷阱?
// Member operator
Number& Number::operator+= (const Number &rhs)
{
Impl->Value += rhs.Impl->Value; // Obviously this is more complicated
return *this;
}
// Non-member non-friend addition operator
Number operator+(Number lhs, const Number &rhs)
{
return lhs += rhs;
}