运算符重载,成员和非成员功能,哪一个优先? [英] operator overloading, member and non-member function, which one has priority?
问题描述
说我有一个Complex
数字类,并且operator+
作为成员函数和全局函数都被重载了两次,例如:
Say I have a Complex
number class and operator+
is overloaded twice, both as a member function and as a global function, for example:
class Complex {
public:
Complex operator+(const Complex& c);
};
Complex operator+(const Complex& a, const Complex& b);
在主函数中,我将调用operator +,如下所示:
And in the main function I will call the operator+ like follows:
Complex a, b;
Complex c = a + b;
将调用哪个operator+
函数?谢谢!
Which operator+
function will be called? Thanks!
推荐答案
一般来说,与非成员相比,成员不是首选,反之亦然.将使用C ++的重载解析规则来选择一个或另一个.
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.
出于重载解析的目的,成员函数被视为具有隐含对象参数(第13.3.1/2节).所以
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);
将
视为具有两个参数:原始的const Complex& c
和另一个Complex&
,它引用用于调用成员函数的对象(实际上是*this
).
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
).
假设我们有两个Complex
变量:
Complex c1, c2;
c1
和c2
都不是const
,因此为了通话
Both c1
and c2
are non-const
, so in order to call
c1.operator+(c2)
作为const
引用的参数c
必须绑定到非const
自变量c2
.
the parameter c
, which is a const
reference, has to bind to the non-const
argument c2
.
另一方面,打电话给
operator+(c1, c2)
分别是const
引用的
参数a
和b
必须绑定到非const
对象c1
和c2
.
both parameters a
and b
, which are const
references, have to bind to non-const
objects, c1
and c2
.
成员operator+
更好,因为const Complex&, Complex&
对于c1, c2
的匹配度比const Complex&, const Complex&
更佳,因为它执行的资格转换较少. (§13.3.3.2/3)
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)
如果将成员operator+
的声明更改为
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.
这篇关于运算符重载,成员和非成员功能,哪一个优先?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!