函数重载分辨率与const

时间:2013-06-11 10:23:39

标签: c++

考虑一下

#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&amp; x)时,它会有什么不同 和一个函数本身const ex - fun(int x)const而重载决议

  3. 尝试各种组合还有一些疑问,所以欢迎在重载决议时解释const的作用的任何通用答案

1 个答案:

答案 0 :(得分:2)

声明会忽略顶级常量,因此fun(const int x)fun(int x)相同。

当然它会与ref版本冲突,几乎没有任何意义。如果您寻找rvalues添加fun(int &&x),尽管它通常与用户定义的类型一起使用

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

相关问题