You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C++如何调用类中const修饰的常量引用重载getter函数

核心原因

const成员函数与非const成员函数构成重载时,编译器的重载匹配规则只和调用函数的对象本身的const限定有关,和接收返回值的变量类型完全无关。
你的代码中c是非const类型的MyClass实例,因此不管你用普通int&还是const int&类型的变量接收返回值,重载决议都会优先匹配非const版本的getElement(),两次调用拿到的都是myArray[0]的值0,自然不会触发返回myArray[1]的const版本。

调用const版本的正确方式

要触发const版本的getElement(),必须保证调用函数的对象带有const限定,常用实现方式有三类:

  • 直接定义const类型的实例调用
const MyClass const_c;
const int& b = const_c.getElement(); // 匹配const版本
  • 给原对象绑定const引用后调用,不需要拷贝对象
MyClass c;
const MyClass& const_ref = c;
const int& b = const_ref.getElement(); // 匹配const版本
  • 直接对原对象做const转换后调用,无需额外定义变量
    • C++17及以上版本推荐用标准库工具std::as_const,写法更简洁安全:
    MyClass c;
    const int& b = std::as_const(c).getElement(); // 匹配const版本
    
    • 兼容C++17以前的旧标准,可以用const_cast手动添加const限定:
    MyClass c;
    const int& b = const_cast<const MyClass&>(c).getElement(); // 匹配const版本
    
运行验证

按上述方法修改main函数后,运行结果符合预期:

a = 0
b = 10

注意:禁止使用const_cast移除const对象本身的const限定去调用非const成员函数,该操作会触发未定义行为。

内容的提问来源于stack exchange,提问作者user16695704

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.28 05:51:15