是否有一个规范或推荐的模式用于实现算术运算过载在C++的数喜欢的类?

从C++常见问题,我们有一个例外安全的分配操作者,避免了最大的问题:

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;
}
有帮助吗?

解决方案

在Bjarne Stroustrup的书“ C ++编程语言”中,在第11章(专门讨论运算符重载的那个)中,他经历了一个复数类型的类(第11.3节)。

我从该部分注意到的一件事是他实现了混合类型操作......这可能是任何数字类所期望的。

一般来说,你所拥有的东西看起来不错。

其他提示

编写任何运算符时要考虑的重要事项是成员运算符不会对左参数进行转换:

struct example {
  example(int);
  example operator + (example);
};

void foo() {
  example e(3), f(6);
  e + 4; // okay: right operand is implicitly converted to example
  e + f; // okay: no conversions needed.
  6 + e; // BAD: no matching call.
}

这是因为转换从不适用于成员函数的 this ,这扩展到了运算符。如果操作符是全局命名空间中的 example operator +(example,example),则它将编译(或者如果使用了pass-by-const-ref)。

因此, + - 等对称运算符通常实现为非成员,而复合赋值运算符如 + = 并且 - = 是作为成员实现的(它们也会更改数据,这意味着它们应该是成员)。并且,由于您希望避免代码重复,因此可以根据复合赋值来实现对称运算符(如在代码示例中,尽管约定建议在函数内部使用临时代码)。

《公约》是编写 operator+(const T&)operator-(const T&) 在条款 operator+=(const T&)operator-=(const T&).如果它是有意义的加减法,从基本类型,然后你应该写入一个构造,构建的目从原始的类型。然后载的经营者还将作为原始种类,因为编译器会打电话的适当构造含蓄地.

正如你自己,你应该避免给予访问权限职能,不需要它。但在你的上方的代码对 operator+(Number, const Number&) 我会亲自做的两个参数const引用和使用的温度。我认为这不足为奇的评论以下你错过了这个问题;除非你有一个很好的理由不,避免意外和技巧,以作为明显,因为可能。

如果你想要你的代码来与其他数字类型,说 std::complex, ,注意循环转换。就是,没有提供 operator OtherNumeric()Numeric 如果 OtherNumeric 提供一个构造,需要一个 Numeric 参数。

传统的做法是根据operator = X
编写运算符X. 传统上标准运算符的所有参数都是const

// Member operator
// This was OK
Number& Number::operator+= (Number const& rhs) 
{
    Impl->Value += rhs.Impl->Value; // Obviously this is more complicated
    return *this;
}

// Non-member non-friend addition operator
Number operator+(Number const& lhs,Number const& rhs)
{
     // This I would set the lhs side to const.
     // Make a copy into result.
     // Then use += add the rhs
     Number result(lhs);
     return result += rhs;
}

你提到了赋值运算符。
但是你没有提到复制构造函数。由于您的类拥有RAW指针的所有权,我希望您也可以定义它。传统上,Assignment运算符是根据复制构造函数编写的。

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top