为什么引用const可以在for语句中重新分配? [英] Why reference const can be re-assigned in for-statement?

查看:58
本文介绍了为什么引用const可以在for语句中重新分配?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是C ++的新手,对此我感到困惑:

I'm new to C++, and I'm confused about this:

vector<int> v = { 1,2 };
const int &r1 = v[0];
//r1 = v[1];  // compiler will show error.

我了解引用const r1 不能重新分配.但是请看下面的代码:

I understand that reference const r1 cannot be re-assigned. But look at the codes below:

for (const int &r2 : v) cout << r2;

为什么那不会出错?引用const r2 被分配了两次,对吧?

Why wouldn't that go wrong? The reference const r2 is assigned twice, right?

推荐答案

否,未分配两次. r2 从迭代开始(循环体上的一轮循环)到迭代结束一直存在.在下一次迭代中, r2 是另一个具有相同名称的对象.每次迭代都有自己的 r2 ,并且每个迭代都分别初始化.

No it's not assigned twice. r2 exists from the start of the iteration (a single round over the loop body) until the end of the iteration. r2 in the next iteration is another object by the same name. Each iteration has their own r2 and each of them is initialized separately.

这篇关于为什么引用const可以在for语句中重新分配?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆