在Page 562 C++编程语言4e中,作者展示了两个函数:
char& operator[](int n) {}
char operator[](int n) const {}
Run Code Online (Sandbox Code Playgroud)
如果我写
char c = someObj[2];
Run Code Online (Sandbox Code Playgroud)
由于分辨率没有处理返回类型,然后,将选择哪个功能?
我做了几次尝试,它只是为了调用char& operator[](int n) {},我认为这里定义的const函数只是为了让它有机会在需要const的某些上下文中调用.但我不太确定.
这是我的测试代码:
#include <iostream>
using namespace std;
class A {
private:
char p[10] = "abcdefg";
public:
char operator[](int n) const {
cout << "const function" << endl;
return p[n];
}
char& operator[](int n) {
cout << "plain function" << endl;
return p[n];
}
};
int main() {
A a;
a[2];
const char &c = a[4];
}
Run Code Online (Sandbox Code Playgroud)
在重载决策中不考虑返回类型.将根据调用运算符的对象的const限定来选择重载:
int main() {
A a;
a[2];
const char &c = a[4];
const A b;
b[2];
const char &d = b[4];
}
Run Code Online (Sandbox Code Playgroud)
这个输出是:
plain function
plain function
const function
const function
Run Code Online (Sandbox Code Playgroud)