指向临时变量的引用

 c++规定指向临时变量的引用只能为常数,具体看看代码了

什么是临时变量又怎么产生的呢,可以看看一下代码

 


void f(short const & b)
{}

int _tmain(int argc, _TCHAR* argv[])
{
    
int i = 20;
    
short const & b = i;//i is not a short, so generate a short variable as a temporary variable during the convert
    i = 0;
    f(i);
//i is not a short, so generate a short variable as a temporary variable during the convert
    i = 0;
    cout 
<< i << "," << b << endl; //output : 0, 20 because b is a reference to a temporary variable
    return 0;
}

 

对于临时变量,只能用常量的引用指向之。否则下面代码将不能编译通过

void f(short & b)
{}

int _tmain(int argc, _TCHAR* argv[])
{
    
int i = 20;
    
short & b = i;// can not set a non-const referenct to temporary variable
    i = 0;
    f(i);
// can not set a non-const referenct to temporary variable
    return 0;
}

有人会问指针呢???指针无论是const或是non-const在这种情况下都会编译失败的

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值