【问题标题】:Why is the method with const used instead of the first method which has no const为什么使用带有 const 的方法而不是第一个没有 const 的方法
【发布时间】:2018-07-02 08:45:46
【问题描述】:
void print( int & a ){ cout << a << endl; }
void print( const int & a ){ cout << 2*a << endl; }
void print( float a ){ cout << 3*a << endl; }

为什么2print(1) 的输出?

【问题讨论】:

  • 1 是不是常数?
  • 第一个重载不可行 - 右值不能绑定到非 const 左值引用。
  • @Asad Masroor 再添加一个重载函数 void print( int &&a ) { std::cout
  • @UKMonkey - VC6 实际上实现了循环变量的proposed 标准。然后在编译器发布几个月后,在标准发布之前修改规则。能否解释为什么 MS 自那以后一直不愿实施新提案?

标签: c++ function methods constants overload-resolution


【解决方案1】:

这个问题的主旨是你需要知道匿名临时对象不能绑定到非const的引用,他们可以绑定到const的引用。

1 是 int 类型的匿名临时。

因此const int&amp; 绑定受到重载决议的青睐。

某些编译器(旧版 MSVC)会错误地允许绑定到 int&amp;。在标准 C++ 中,如果缺少 const int&amp; 重载,则将调用 float 重载。

【讨论】:

    【解决方案2】:

    对于所有三个重载:

    1. (void print( int &amp; a ){ cout &lt;&lt; a &lt;&lt; endl; }) 第一个重载没有被调用,因为它只接受一个变量。 (除非您有旧的 MSVC 编译器)。
    2. (void print( const int &amp; a )) 第二个重载是const int&amp; 类型,它可以接受int 类型的临时变量或int 类型的变量。
    3. (void print( float a )) 第三个重载有一个 float 类型的参数,如果没有 int 类型的重载,它将被调用。

    因此,由于存在接受 int 类型临时变量的重载,因此选择第二个重载而不是第三个。

    【讨论】:

      猜你喜欢
      • 2016-12-26
      • 2017-10-18
      • 2011-05-08
      • 1970-01-01
      • 1970-01-01
      • 2022-10-23
      • 1970-01-01
      • 2014-05-18
      • 1970-01-01
      相关资源
      最近更新 更多