为什么用代码块重置引用时为什么没有出现错误?

问题描述 投票:0回答:1

在下面的代码中

using namespace std;

int main(){
    int x=4;
    int y=5;
    cout << x <<endl;
    int& foo = x;

    // foo is now a reference to x so this sets x to 56
    foo = 56; //reseting the reference foo
    cout << x <<endl;
    cout << foo <<endl;


    foo= y; //this is supposed to be forbidden 
    cout << foo <<endl; // but I am getting foo=5

return 1;
}

Codeblocks编译正常,我在最后一个指令中得到foo = 5。对于我阅读的内容,您无法重新设置引用以使其引用另一个对象,所以我一直期待一个错误,这是怎么回事?

c++ pass-by-reference
1个回答
1
投票
一旦创建了引用,任何使用引用变量的尝试都等同于使用分配给它的对象。
© www.soinside.com 2019 - 2024. All rights reserved.