c – 重载运算符 – ()作为自由函数的意义,而不是成员函数?

我正在阅读 the C++ FAQ.在那里,我发现操作符重载使用的指南中有一点:

If you provide constructive operators,they should allow promotion of the left-hand operand (at least in the case where the class has a single-parameter ctor that is not marked with the explicit keyword). For example,if your class Fraction supports promotion from int to Fraction (via the non-explicit ctor Fraction::Fraction(int)),and if you allow x – y for two Fraction objects,you should also allow 42 – y. In practice that simply means that your operator-() should not be a member function of Fraction. Typically you will make it a friend,if for no other reason than to force it into the public: part of the class,but even if it is not a friend,it should not be a member.

为什么作者写的是operator-()不应该是成员函数

如果我将operator-()作为成员函数,还有什么后果呢?

解决方法

这里是作为成员函数的运算符的分数:
class Fraction
{
    Fraction(int){...}

    Fraction operator -( Fraction const& right ) const { ... }
};

有了它,这是有效的代码

Fraction x;
Fraction y = x - 42;

其等效于x.operator-(Fraction(42));但这不是:

Fraction z = 42 - x;

因为42没有成员函数运算符(当然,它甚至不是一个类).

但是,如果您将运算符声明为自由函数,则转换操作将适用于其两个参数.所以这

Fraction z = 42 - x;

变成这样

Fraction z = Fraction(42) - x;

这相当于运算符 – (分数(42),x)).

相关文章

本程序的编译和运行环境如下(如果有运行方面的问题欢迎在评...
水了一学期的院选修,万万没想到期末考试还有比较硬核的编程...
补充一下,先前文章末尾给出的下载链接的完整代码含有部分C&...
思路如标题所说采用模N取余法,难点是这个除法过程如何实现。...
本篇博客有更新!!!更新后效果图如下: 文章末尾的完整代码...
刚开始学习模块化程序设计时,估计大家都被形参和实参搞迷糊...