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