【问题标题】:Which overloaded version of operator will be called将调用哪个重载版本的运算符
【发布时间】:2010-01-25 19:22:16
【问题描述】:

假设我在一个类中声明了下标运算符

  1. char& operator[] (int index);
  2. const char operator[](int index) const;

在什么条件下调用第二个重载。是否仅通过const object 调用。

在以下场景中将调用哪个版本的运算符。

const char res1 = nonConstObject[10]; 
nonConstObject[10];

【问题讨论】:

    标签: c++ operator-overloading constants


    【解决方案1】:

    第一个被调用。不要被返回值弄糊涂了;只有参数被认为是选择方法。在这种情况下,隐式 this 是非常量的,因此调用非常量版本。

    【讨论】:

      【解决方案2】:

      只能从常量实例调用常量方法。由于 nonConstObject 未定义为 const,因此两个调用都将针对非 const 重载运算符。

      【讨论】:

      • 非常量方法只能被非常量实例调用。但是可以为 bot const 和非 const 实例调用 const 方法。
      猜你喜欢
      • 2013-03-03
      • 2014-11-18
      • 2020-12-23
      • 1970-01-01
      • 2017-12-23
      • 1970-01-01
      • 2019-03-03
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多