[英]Significance of overloading operator - () as free function & not a member function?
I was reading the C++ FAQ . 我正在阅读C ++ FAQ 。 There I found a point in the guideline for operator overloading uses:
在那里我发现操作符重载使用指南中有一点:
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).
如果您提供构造性运算符,则它们应该允许提升左侧操作数(至少在类具有未使用explicit关键字标记的单参数ctor的情况下)。 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.
例如,如果您的类Fraction支持从int到Fraction的提升(通过非显式ctor :: Fraction(int)),并且如果允许x-y用于两个Fraction对象,则还应允许42-y。 In practice that simply means that your operator-() should not be a member function of Fraction.
在实践中,这仅仅意味着您的operator-()不应该是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.
通常你会把它变成朋友,如果没有其他原因而不是强迫它进入公众:类的一部分,但即使它不是朋友,它也不应该是成员。
Why has the author written that operator-() should not be member function? 为什么作者写了operator-()不应该是成员函数?
What are the bad consequences if I make operator-() as member function and what are other consequences? 如果我将operator-()作为成员函数以及其他后果会有什么不良后果?
Here is Fraction
with the operator as a member function: 这是与运算符作为成员函数的
Fraction
:
class Fraction
{
Fraction(int){...}
Fraction operator -( Fraction const& right ) const { ... }
};
With it, this is valid code: 有了它,这是有效的代码:
Fraction x;
Fraction y = x - 42;
and its equivalent to x.operator-( Fraction(42) )
; 和它相当于
x.operator-( Fraction(42) )
; but this is not: 但这不是:
Fraction z = 42 - x;
Because 42
has no member function operator -
in it (of course, its not even a class) . 因为
42
没有成员函数operator -
在它中(当然,它甚至不是一个类) 。
However, if you declare your operator as a free function instead, conversion operations apply to both of its arguments. 但是,如果您将运算符声明为自由函数,则转换操作将应用于其两个参数。 So this
所以这
Fraction z = 42 - x;
turns into this 变成这个
Fraction z = Fraction(42) - x;
which is equivalent to operator-( Fraction(42), x )
. 这相当于
operator-( Fraction(42), x )
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.