T
thomas
#include<iostream>
using namespace std;
class foo{
int ar[30];
public:
const int& operator[](unsigned index) const{
cout<<"one"<<endl;
return ar[index];
}
int& operator[](unsigned index){
cout<<"two"<<endl;
return ar[index];
}
};
int main(){
foo f;
cout<<f[3]<<endl;
// f[3] = 3; //(1)
cout<<f[3]<<endl;
}
---------------------code----------------------
The FAQ 18.12 (http://www.parashift.com/c++-faq-lite/const-
correctness.html) gives a similar example to the above one.
I expected the "const" version is called since expression (1) is
commented.
But I found that only the non-const version is called whether (1) is
commented or not.
Do const overloading work in this case? Any more details?
using namespace std;
class foo{
int ar[30];
public:
const int& operator[](unsigned index) const{
cout<<"one"<<endl;
return ar[index];
}
int& operator[](unsigned index){
cout<<"two"<<endl;
return ar[index];
}
};
int main(){
foo f;
cout<<f[3]<<endl;
// f[3] = 3; //(1)
cout<<f[3]<<endl;
}
---------------------code----------------------
The FAQ 18.12 (http://www.parashift.com/c++-faq-lite/const-
correctness.html) gives a similar example to the above one.
I expected the "const" version is called since expression (1) is
commented.
But I found that only the non-const version is called whether (1) is
commented or not.
Do const overloading work in this case? Any more details?