temporary of type `int'

 

 执行下面的语句你会得到错误:

 invalid initialization of non-const reference of type ‘int&’ from a temporary of type ‘int’

 

 

int &z = 12;

 

12 这个值是没有名字的,所以它是临时的(temporary),不能将一个temporary的变量赋值给一个引用(&修饰的)类型。

 

但是可以将temporary量赋值给const修饰的引用类型。 这个是为什么呢?

 

国外网站对此有激烈讨论:

http://stackoverflow.com/questions/8293426/error-invalid-initialization-of-non-const-reference-of-type-int-from-an-rval?rq=1

 

 

#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);
}
~       
 
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值