可能重複:
How come a non-const reference cannot bind to a temporary object?傳輸參數爲const參考與正常參考
有這樣的代碼:
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引用傳遞臨時對象? –