运算符重载,成员和非成员功能,哪一个优先? [英] operator overloading, member and non-member function, which one has priority?

查看:75
本文介绍了运算符重载,成员和非成员功能,哪一个优先?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

说我有一个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;

c1c2都不是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引用的

参数ab必须绑定到非const对象c1c2.

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆