简体   繁体   中英

Member vs Non-member operator overloading

I am trying to understand operator overloading in C++ and I ran into this piece of code:

class Imaginary {
    double re,im ;
    public:
    Imaginary ( double r, double i=0 ) : re(r), im(i) {}

    Imaginary operator - ( void ) const;                // member
    Imaginary operator + ( const Imaginary& x ) const;  // member

    friend Imaginary operator + ( double a, const Imaginary& b ); // non-member ?
};

which supposed to show the use of non-member overloading. But I don't understand how is it non-member when it's declared inside of class? Or does it depend on the number of parameter, as + is binary operation, so with 2 parameters it's considered non-member and with 1 member?

This line declares op+ as a non-member friend. Meaning that despite it being a non member it can see Imaginary's private members.

friend Imaginary operator + ( double a, const Imaginary& b ); 

The implementation of the operator will be outside of the class.

A friend declaration is injected into the namespace surrounding the class definition where it appears. That is, the declaration (namespace added to later clarification):

namespace foo {
    class Imaginary {
        // ...
        friend Imaginary operator+ (double a, Imaginary const& b);
    };
}

Actually does two things: it declares a function and it states that this function is allowed to access all members of the class Imaginary . The function declared is

foo::Imaginary foo::operator+ (double a, foo::Imaginary const& b);

There is a big difference between these two operators

Imaginary operator + ( const Imaginary& x ) const;  // member

friend Imaginary operator + ( double a, const Imaginary& b ); // non-member ?

In the first class member operator the left operand is always of type Imaginary. The second operand can be of type double because there is conversion constructor

Imaginary ( double r, double i=0 ) : re(r), im(i) {}

that allows implicitly convert a double value to an object of type Imaginary.

The friend operator allows to specify a double number as the first operand of the operation. Again if a double number will be specified as the first operand the conversion constructor will be called and in fact you will get expression

Imaginary + Imaginary.

Thus the friend operator appends the class member operator allowing the following expressions

Imaginary + Imaginary // class member operator will be called
Imaginary + double// class member operator will be called
double + Imaginary // the friend operator will be called

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