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)).