執行下面的語句你會得到錯誤:
invalid initialization of non-const reference of type ‘int&’ from a temporary of type ‘int’
int &z = 12;
12 這個值是沒有名字的,所以它是臨時的(temporary),不能將一個temporary的變量賦值給一個引用(&修飾的)類型。
但是可以將temporary量賦值給const修飾的引用類型。 這個是爲什麼呢?
國外網站對此有激烈討論:
#include <stdio.h> template <class T> T returnSelf(T &v){ return v; } template <class T> int compare (const T& v1,const T& v2){ if(v1 < v2) return -1; if(v1 > v2) return 1; return 0; } int main(){ int i = 1; float j = 2.0f; double k = 3.0; printf("i is :%d\n",returnSelf(i)); printf("j is :%f\n",returnSelf(j)); printf("k is :%f\n",returnSelf(k)); compare("hi","88");//"hi" and "hi1" are different styles. int ret = compare(i, 10);//can't set temporary value to reference. printf("compare i with 10, the result is :%d",ret); } ~