为什么非const方法会隐藏const重载? [英] Why does non-const method hide const overload?

查看:70
本文介绍了为什么非const方法会隐藏const重载?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给出以下代码:

class A
{
public:
    A(): value( 0 ) {}

    int* get()
    {
        return &value;
    }

    const int& get() const
    {
        return value;
    }

private:
    int value;
};

int main()
{
    A a;
    const int& ref_value = a.get();
}

导致以下编译错误:

prog.cpp: In function 'int main()':
prog.cpp:23:35: error: invalid conversion from 'int*' to 'int'
      const int& ref_value = a.get();
                                   ^

似乎带有const修饰符的重载get()方法确实会被完全忽略,并且编译器只能看到它的非const定义.这是可以理解的,因为对象不是恒定的.一种解决方案是使 a 对象恒定.尽管还有其他两种解决方案可以使代码可编译:

It seems that the overloaded get() method with const modifier does get ignored completely and the compiler sees only the non-const definition of it. It is somehow understandable since the a object is not constant. One solution would be to make the a object constant. Though there are other two solutions that makes the code compileable:

  1. 通过不同的名称或添加的其他参数来更改const get()方法的签名.

  1. Change the signature of the const get() method by different name or other parameters added.

int* get();
const int& get_changed() const; <-- this gets called

  • 更改非常量get()方法以返回引用而不是指针.

  • Change the non-const get() method to return a reference instead pointer.

    int& get(); <-- this gets called
    const int& get() const; 
    

  • 尽管

    int* get();
    const int& get() const;
    

    我们遇到了编译器错误.

    we have a compiler error.

    让我感到困惑的是所有这些行为背后的原因.

    What puzzles me is the reason behind all of these behavior.

    推荐答案

    当同时具有相同参数的相同函数的const和非const重载时,调用该函数取决于 有关要在其上调用该函数的对象的const ness.因此,调用非const a 必须调用非const重载.

    When you have both a const and non-const overload of the same function with the same parameters, which one gets called depends only on the constness of the object on which you're invoking the function. So invoking on a non-const a must call the non-const overload.

    与这种情况完全相同:

    void foo(int *p);
    
    void foo(const int *p);
    
    
    int main()
    {
      int i;
      const int ci;
      foo(&i);  // Calls the first overload
      foo(&ci);  // Calls the second overload
    }
    

    可以在非const限定对象上调用

    限定const的函数 ,但这需要从非常量到常量"的转换.如果存在不需要这种转换的重载(更好的匹配),则将是首选.

    A const-qualified function can be called on a non-const-qualified object, but that requires a "nonconst to const" conversion. If there's an overload which doesn't require such a conversion (is a better match), it will be preferred.

    这篇关于为什么非const方法会隐藏const重载?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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