kMa*_*ter 3 c++ polymorphism overloading reference 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;
}
Run Code Online (Sandbox Code Playgroud)
我希望第二次和第三次调用a.get_ref()运行第二版get_ref()方法(并输出const标准错误).但看起来总是第一个版本被调用.如何实现两个不同的'getter'并确保根据上下文调用正确的版本?即,至少在第三次通话时
const int& y = a.get_ref();
Run Code Online (Sandbox Code Playgroud)
第二个版本执行?(一个不优雅的解决方案是使用不同的名称,例如get_ref,get_const_ref但我试图看看是否可以避免.)
重载决策不依赖于返回值,而只依赖于参数,包括要为成员函数调用的对象.a是一个非const对象,然后a.get_ref(),总是会调用非const成员函数.
您可以将其const强制转换为要调用的const版本:
const_cast<const A&>(a).get_ref();
Run Code Online (Sandbox Code Playgroud)
顺便说一句:给他们不同的名字并不是一个坏主意.这就是我们在STL中使用std :: cbegin和std :: cend的原因.
| 归档时间: |
|
| 查看次数: |
404 次 |
| 最近记录: |