如何调用非常量重载
How to call a non-const overload?
void func(const int& i)
和void func(int& i)
之间有什么区别。如果const在顶级被截断,是否有可能调用第二个重载?为什么首选const重载?以下将始终选择第一个过载:
func(42);
func(int{42});
int i = 42;
func(i);
int &j = i;
func(j);
func(i + 1);
哎呀,我明白我现在的问题是什么了。我在两个函数中都键入了cout << "constn"
,所以看起来它总是调用第一个重载。对不起,伙计们。
const
是对自己和其他开发人员的一个提示,即您不打算修改观察到的对象。如果参数为const:,则选择const重载
#include <iostream>
void f(const int&)
{
std::cout << "f(const int&)n";
}
void f(int&)
{
std::cout << "f(int&)n";
}
int main()
{
int a = 0;
const int b = 0;
int& c = a;
const int& d = a;
f(a);
f(b);
f(c);
f(d);
}
这将输出
f(int&)
f(const int&)
f(int&)
f(const int&)
请参阅此演示。
正如您所看到的,它并不总是const
过载。
void func(const int& i)
和void func(int& i)
之间有什么区别。
void func(const int& i)
和void func(int& i)
之间的区别在于,在第一个函数中不能更改i
,而在第二个函数中可以更改。
甚至可以调用第二个过载吗?
如果参数不是const
,则会选择第二个函数。
为什么首选
const
过载?
这取决于情况。如果计划更改const
的值,则不能使用它。当您希望确保不会意外或有意地更改变量时,应该使用const
。看看这篇文章:在C++中尽可能使用const?了解更多信息。
相关文章:
- #定义c-预处理器常量..我做错了什么
- 用C++中的一个变量定义一个常量
- 什么时候在C++中返回常量引用是个好主意
- 代理对象的常量正确性
- 我想将一个对T类型的非常量左值引用绑定到一个T类型的临时值
- 通过多个头文件使用常量变量
- 在cuda线程之间共享大量常量数据
- 不能在初始值设定项列表中将非常量表达式从类型 'int' 缩小到'unsigned long long'
- 有没有什么方法可以使用一个函数中定义的常量变量,也可以由c++中同一程序中的其他函数使用
- 是默认情况下分配给char数组常量的值
- 私有类型的静态常量成员
- OpenGL大的3D纹理(>2GB)非常慢
- 类似枚举的计算常量
- 递归模板化函数不能分配给具有常量限定类型"const tt &"的变量"state"
- 使用常量键但非常量值进行映射
- 为什么`is_open()`非常常量
- 从getter方法返回常量和非常量值
- 阻止const类函数在引用成员上调用非常常量类函数
- C++初始化非常大的常量数组,最佳实践
- 提高c++中非常大的常量的可读性