可能的重复:
为什么非常量引用不能绑定到临时对象?
有这样的代码:
void fun_ref(int& par){}
void fun_const_ref(const int& par){}
int main(){
//fun_ref(2); error: invalid initialization of non-const reference of type ‘int&’ from a temporary of type ‘int’
fun_const_ref(2);
char var = 3;
//fun_ref(var); error: invalid initialization of reference of type ‘int&’ from expression of type ‘char’
fun_const_ref(var);
return 0;
}
为什么常量引用可以传递右值和与函数参数类型不同的数据类型,但非常量引用却不能?
当参数是 const 引用并且传递的参数不是该类型但存在到该类型的隐式转换时,实现会将值保存在临时变量中并使用此类临时变量作为参数。所以 const 版本没有引用char var
but to int __temp
.
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)