简体   繁体   中英

Significance of overloading operator - () as free function & not a member function?

I was reading the 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). 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.

Why has the author written that operator-() should not be member function?

What are the bad consequences if I make operator-() as member function and what are other consequences?

Here is Fraction with the operator as a member function:

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) ) ; but this is not:

Fraction z = 42 - x;

Because 42 has no member function operator - in it (of course, its not even a class) .

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM