【发布时间】:2011-12-16 16:13:21
【问题描述】:
可能重复:
How come a non-const reference cannot bind to a temporary object?
有这样的代码:
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;
}
为什么常量引用可以传递右值和与函数参数类型不同的数据类型,而非常量引用却不行?
【问题讨论】:
标签: c++