In Page 562 The C++ Programming Language 4e , the author shows two functions:
char& operator[](int n) {}
char operator[](int n) const {}
If I write
char c = someObj[2];
Since the resolution didn't take care of the return type, and then, which function will be chosen?
I made several tries and it just to call char& operator[](int n) {}
, and I think the const function defined here just to give it a chance to be able to be called in some context that require a const. But I not quite sure that.
this is my testing code:
#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];
}
The return type is not considered in overload resolution. Your overload will be selected based on the const-qualification of the object the operator is called on:
int main() {
A a;
a[2];
const char &c = a[4];
const A b;
b[2];
const char &d = b[4];
}
The output of this is:
plain function
plain function
const function
const function
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.