为什么认为参考文献在C 底漆第5个中没有变化,以下代码有效

Why a reference is said to be unchanged in C++ primer 5th, how ever this following code works?

本文关键字:有变化 有效 代码 5个 参考文献 为什么      更新时间:2023-10-16

在书中,我们解释说,没有办法参考其他对象,以下代码对C 11。

int i1 = 1, i2 = 0;
int &ri = i1;
ri = i2;

ri不会更改其指向的内容,它会更改指向的值。因此,如果您在i1上打印值,则现在看到它等于0,如果更改i2的值,您会看到它不会影响ri

int main() {
    int i1 = 1, i2 = 0;
    int& ri = i1;
    ri = i2; // i1 == 0
    std::cout << "i1 " << i1 << "n";
    i2 = 5;
    std::cout << "i2 " << i2 << "n";
}

,输出为

i1 0
i2 5

要获得更好的理解,请尝试以下操作:

int i1 = 1, i2 = 0;
int &ri = i1;          // ri refers to i1 and this won't change afterwards
cout << ri <<endl;     // same value as i1, so 1
i1 = 3; 
cout << ri <<endl;     // still same value as i1, but now it's 3
ri = 5; 
cout << i1 <<endl;     // same value as ri since both name refer to the same variable, so 5
ri = i2;               // ri still refers to i1, but copies value of i2 in it
cout << i1<<endl;      // i1 was overwritten through ri
ri = 7;  
cout << i1 << endl     // i1 was overwritten again through ri
     <<i2 <<endl;      // but i2 stays unchanged, since ri does not refer to it.  

为什么说参考在C 底漆中没有变化,以下代码有效吗?

因为可以更改整数的值。这就是ri = i2所做的。参考不受影响;它仍然指同一对象。引用对象的值受到影响。结果与您写了i1 = i2