使用const解析函数重载
Function overloading resolution with const
考虑一下
#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;
}
编译这个会产生歧义,但没有人说这是由于乐趣(const int x),但删除这个使代码得到正确编译
设置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
相关文章:
- 为什么使用SFINAE而不是函数重载
- 为什么我不能在 C++ 中的特定函数重载中调用同一函数的任何其他重载?
- c++:可变模板和函数重载
- 在缺少函数重载时抛出异常,并带有 std::variant 而不是编译时错误
- 解决模板成员函数重载
- 为什么不允许成员函数和非成员函数之间的函数重载?
- 推断模板化函数中的函数重载
- C++复制函数重载导致"must be a nonstatic member function"错误
- 为什么 std::sort 找不到合适的(静态成员)函数重载?
- 可变参数泛型 lambda 和函数重载
- C++中的函数重载和继承
- 当有右值构造函数可用时,为什么从右值调用类引用构造函数重载?
- C/C++ 可变参数宏函数重载
- 将基类的成员函数重载到其他派生类C++
- C++ 函数重载匹配
- C++函数重载,具体步骤是什么
- C++:使用 param pack 显式调用函数重载
- 隐式生成的函数重载用于右值参数?
- 使用函数重载输入运算符
- 运算符重载函数上的函数重载