我正在阅读 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-() 作为成员函数会有什么不良后果,还有什么其他后果?
最佳答案
这里是 Fraction
,运算符作为成员函数:
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
里面没有成员函数operator-
(当然,它连一个类都算不上)。
但是,如果您将运算符声明为自由函数,则转换操作适用于它的两个参数。所以这个
Fraction z = 42 - x;
变成这样
Fraction z = Fraction(42) - x;
相当于 operator-( Fraction(42), x )
。
关于c++ - 重载运算符 - () 作为自由函数而不是成员函数的意义?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10958698/