考虑以下代码:
#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_ref
和 get_const_ref
但我正在尝试看看是否可以避免这种情况。)
最佳答案
重载解析不依赖于返回值,只依赖于参数,包括成员函数调用的对象。 a
是一个非常量对象,那么对于a.get_ref()
,总是会调用非常量成员函数。
您可以将其转换为 const
以调用 const 版本:
const_cast<const A&>(a).get_ref();
顺便说一句:给他们不同的名字是个不错的主意。这就是为什么我们有 std::cbegin
和 std::cend
在 STL 中。
关于c++ - 为什么不调用具有const引用返回值的重载方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43734405/