c++ - 为什么不调用具有const引用返回值的重载方法?

标签 c++ reference polymorphism overloading const-reference

考虑以下代码:

#include <iostream>

using namespace std;

class A {
    private:
    int x;
    public:
    int& get_ref() {
        cerr << "non const" << endl;
        return x;
    }

    const int& get_ref() const {
        cerr << "const" << endl;
        return x;
    }
};

int main () {
    A a;
    a.get_ref() = 10;

    cout << a.get_ref() << endl;

    const int& y = a.get_ref();

    return 0;
}

我希望第二次和第三次调用 a.get_ref() 来运行第二个版本的 get_ref() 方法(并输出 const 关于标准错误)。但看起来总是第一个版本被调用。我如何实现两个不同的“getter”并确保根据上下文调用正确的版本?即,至少对于第三次调用

const int& y = a.get_ref();

第二个版本执行了吗? (一个不优雅的解决方案是使用不同的名称,例如 get_refget_const_ref 但我正在尝试看看是否可以避免这种情况。)

最佳答案

重载解析不依赖于返回值,只依赖于参数,包括成员函数调用的对象。 a是一个非常量对象,那么对于a.get_ref(),总是会调用非常量成员函数。

您可以将其转换为 const 以调用 const 版本:

const_cast<const A&>(a).get_ref();

顺便说一句:给他们不同的名字是个不错的主意。这就是为什么我们有 std::cbeginstd::cend在 STL 中。

关于c++ - 为什么不调用具有const引用返回值的重载方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43734405/

相关文章:

c++ - C++中的多态迭代器

c++ 如何在运行时通过错误代码给用户一个合适的异常?

c# - 如何编码以获得适当的 CPU 使用率?

c++ - Concert 技术中的按列建模 - 列生成

reference - 生命周期不匹配 - 返回引用的可变变量

java - List<Dog> 是 List<Animal> 的子类吗?为什么 Java 泛型不是隐式多态的?

c++ - 删除指针的后遗症

c++ - 快速排序调试

c++ - 为什么 std::string 引用不能带 char*?