假设String类中有两个重载的成员函数(一个const版本和一个非const版本):
char & String::operator[](int i) //Version 1
{
cout<<"char & String::operator[](int i) get invoked."<<std::endl;
return str[i];
}
const char & String::operator[](int i) const //Version 2
{
cout<<"const char & String::operator[](int i) const get invoked."<<std::endl;
return str[i];
}
还有一段测试代码片段
int main(){
String a;
cout<<a[0]<<endl; //Line 1
a[0]='A'; //Line 2
}
编译器如何决定调用哪个函数?我发现运行程序时总是会调用版本 1。谁能告诉我这是为什么?如何调用版本 2?
最佳答案
如果 a
是 const,将调用第二个重载。
int main(){
const String a;
cout<<a[0]<<endl; // would call const version
a[0]='A'; // will not compile anymore
}
关于c++ - 编译器如何决定调用哪个函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10259757/