执行下面的语句你会得到错误:
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);
}
~
本文探讨了C++中非const引用与const引用初始化的区别,解释了为何不能使用临时变量初始化非const引用,但可以初始化const引用的原因,并附带了一个示例程序。
603

被折叠的 条评论
为什么被折叠?



