4

考虑以下代码:

#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但我想看看是否可以避免这种情况。)

4

2 回答 2

7

重载决议不依赖于返回值,而只依赖于参数,包括为成员函数调用的对象。a是一个非常量对象,那么对于a.get_ref(),非常量成员函数将始终被调用。

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

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

顺便说一句:给他们起不同的名字并不是一个坏主意。这就是我们在 STL 中拥有std::cbeginand的原因。std::cend

于 2017-05-02T09:31:15.873 回答
0

重载决议只关心调用的参数(包括隐含的参数this)。表达式a.get_ref()必须计算为相同的重载,而不管其返回值会发生什么。这是 C++ 的基础,您对此无能为力。

如果要调用const-qualified 版本,请使用const-qualified 对象表达式:

const int& y = const_cast<const A&>(a).get_ref();
于 2017-05-02T09:32:46.843 回答