现在的位置: 首页 > 综合 > 正文

指向临时变量的引用

2013年04月03日 ⁄ 综合 ⁄ 共 805字 ⁄ 字号 评论关闭

 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在这种情况下都会编译失败的

抱歉!评论已关闭.