Members are not preferred over non-members in general, nor vice versa. C++'s overload resolution rules are applied to select one or the other.
A member function, for the purpose of overload resolution, is considered to have an implied object parameter (§13.3.1/2). So
Complex Complex::operator+(const Complex& c);
is treated as though it takes two arguments: the original const Complex& c
, and another Complex&
which refers to the object used to call the member function (in effect, *this
).
Suppose we have two Complex
variables:
Complex c1, c2;
Both c1
and c2
are non-const
, so in order to call
c1.operator+(c2)
the parameter c
, which is a const
reference, has to bind to the non-const
argument c2
.
On the other hand, to call
operator+(c1, c2)
both parameters a
and b
, which are const
references, have to bind to non-const
objects, c1
and c2
.
The member operator+
is better because const Complex&, Complex&
is a better match for c1, c2
than const Complex&, const Complex&
because it performs less qualification conversion. (§13.3.3.2/3)
If you change the declaration of the member operator+
to
Complex Complex::operator+(const Complex& c) const;
then the overload will become ambiguous, and compilation will fail.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…