为什么认为参考文献在C 底漆第5个中没有变化,以下代码有效
Why a reference is said to be unchanged in C++ primer 5th, how ever this following code works?
在书中,我们解释说,没有办法参考其他对象,以下代码对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
。
相关文章:
- 有哪些有效的方法可以消除一组 100 万个字符串>重复数据?
- C++函子,有什么有效的方法吗?
- 只需要知道我在c ++中打印模式的方式是否有效,或者有另一种方法可以有效地做到这一点
- C++ - 这个条件语句写得正确吗?还是有更有效的写法?
- 是否有更有效的方法来生成日期的REGEX字符串
- 是否有一种有效的方法来搜索队列中的关键字并覆盖其值
- 是否有更有效的方法来检查元素是否在给定的区间内
- 用于检查我们是否有有效数独的辅助功能
- 有没有办法有效地更新QML中的CAN数据?
- 有没有有效的方法来"shuffling"载体
- 在C++中,获取/释放原子访问和结合围栏的放松访问之间有什么有效的区别吗
- 从C++输入中收集数据时,是否有更有效的方法可以处理变量
- 有没有有效的方法可以从现在开始生成从范围到 10 天的随机date_time
- 如何确保迷宫总是有一个有效的路径C++
- 双向映射是否有更有效的实现
- 是否有任何有效的方法来获取大型向量
- 对于同一循环的这两个连续组,是否有更有效的解决方案
- 如何在循环中更改 int 变量,如果是这样,是否有更有效的方法
- 设计模式-是否有一个有效的案例可以创建一个立即被销毁且不直接在C++中使用的临时模式
- c++ STL标准是否有变化?