首页 > C++关于引用的问题

C++关于引用的问题

    int getX() { return 3;}
    int& x = getX();//error
    const int& y = getX();//ok

请问,为什么第二行代码会行不通,而加个const却可以???


这篇文章解释的不错,可以看看,http://stackoverflow.com/questions/1565600/how-come-a-non-const-reference-cannot-bind-to-a-temporary-object
主要是因为getX()返回的是一个临时变量


const 只能定义的时候赋值一次,以后就不行了。
引用可以说是类似 const 的指针,但是还是稍微有点区别的。

【热门文章】
【热门文章】