c++ - 编译器如何决定调用哪个函数?

标签 c++ constants overloading

假设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/

相关文章:

c++ - 重载 lambda 函数

c++ - 什么是 undefined reference /未解析的外部符号错误,我该如何解决?

c++ - 将 char 数组转换为 int

c++ - 如何编译具有 'wlanapi.h' 和 'windows.h' 依赖项的 C++ 代码

c++ - cpp 核心指南中的 owner<T*> p 语法

c# - 如何从字符串变量创建常量字符串

java - Android 常量存放在哪里?

c++ - 在 C++ 中递增常量

c++ - 虚继承中的重载虚函数

c# - 我可以定义一个方法来接受 Func<T> 或 Expression<Func<T>> 吗?