使用const解析函数重载

Function overloading resolution with const

本文关键字:函数 重载 const 使用      更新时间:2023-10-16

考虑一下

#include <iostream>
class A
{
public:
  void fun(int x) const
  {
    std::cout<<"int x"<<std::endl;
  }
  void fun(const int x)
  {
    std::cout<<"const int x"<<std::endl;
  }
  void fun(int &x)
  {
    std::cout<<"int &x"<<std::endl;
  }
  void fun(const int &x)
  {
    std::cout<<"const int &x"<<std::endl;
  }
};
int main()
{
  A obj;
  int a = 10;
  const int b = 10;
  int& ref = a;
  const int& ref1 = b;
  obj.fun(a);
  obj.fun(b);
  obj.fun(ref);
  obj.fun(ref1);
  return 0;
}
  1. 编译这个会产生歧义,但没有人说这是由于乐趣(const int x),但删除这个使代码得到正确编译

  2. 设置const ex- fun(const int&x)和函数本身const ex - fun(int x) const while重载解析

尝试不同的组合会有更多的疑问,所以任何解释const在重载解析中的作用的通用答案都是受欢迎的

顶层const在声明中被忽略,因此fun(const int x)fun(int x)相同。

它肯定会与参考版本冲突,几乎没有任何意义。如果您寻找右值添加fun(int &&x),尽管它通常用于用户定义的类型

()后的const限定对象实例——this指针。选择何时使用const A obj