【发布时间】:2017-09-29 18:31:13
【问题描述】:
考虑以下代码:
#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,但我想看看是否可以避免这种情况。)
【问题讨论】:
标签: c++ reference polymorphism overloading const-reference