C ++重载运算符两次,一个返回非const引用,另一个返回const引用,首选项是什么? [英] C++ overload operator twice, one return non-const reference and the other const reference, what is the preference?

查看:91
本文介绍了C ++重载运算符两次,一个返回非const引用,另一个返回const引用,首选项是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我用相同的参数列表两次重载了运算符.但是返回类型不同:

I overload an operator twice with the same parameter list. but with different return type:

T& operator()(par_list){blablabla}    
const T& operator()(par_list){blablabla}

因此,当我调用()运算符时,将基于哪种偏好或情况调用哪个函数?我知道,如果我在const函数下调用(),则必须是const T&一个.

So when I'm calling the () operator, which function would be called based on what preference or situation? I know that if I call () under const function it has to be the const T& one.

我很好奇C ++如何处理这种情况以及默认首选项如何工作.

I'm just curious how C++ deal with such situation and how the default preference works.

谢谢

推荐答案

这些函数不会互相重载;它们具有相同的签名,因此尝试重新定义相同的功能,这是一个错误.返回类型不是函数签名的一部分.要重载一个函数,必须声明另一个具有相同名称,但参数或const/volatile限定符不同的函数-即函数上的限定符,而不是返回类型.

These functions don't overload each other; they have the same signatures, and so the attempt to redefine the same function, which is an error. The return type is not part of a function's signature. To overload a function, you must declare a second function with the same name, but different parameters or const/volatile qualifiers - that is, qualifiers on the function, not the return type.

(它们也不会互相覆盖;覆盖是派生类对其基类的虚函数所做的工作.)

(They don't override each other either; overriding is what derived classes do to their base classes' virtual functions).

定义成员函数的const和非const重载是很常见的. const重载必须声明函数const,而不仅仅是返回类型:

It's common to define a const and a non-const overload of a member function; the const overload must declare the function const, not just the return type:

T& operator()(par_list){blablabla}
const T& operator()(par_list) const {blablabla}
                              ^^^^^

现在,如果将()应用于非const对象,则将调用第一个对象,而将第二个对象应用于const对象.例如:

Now the first will be called if you apply () to a non-const object, and the second on a const object. For example:

Thingy nc;
Thingy const c;

nc(); // calls the first (non-const) overload
c();  // calls the second (const) overload

这篇关于C ++重载运算符两次,一个返回非const引用,另一个返回const引用,首选项是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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