相关疑难解决方法(0)

基于C++ 11范围的循环:按值获取项目或引用const

读取基于范围环的一些例子他们建议两种主要方式1,2,3,4

std::vector<MyClass> vec;

for (auto &x : vec)
{
  // x is a reference to an item of vec
  // We can change vec's items by changing x 
}
Run Code Online (Sandbox Code Playgroud)

要么

for (auto x : vec)
{
  // Value of x is copied from an item of vec
  // We can not change vec's items by changing x
}
Run Code Online (Sandbox Code Playgroud)

好.

当我们不需要更改vec项目时,IMO,示例建议使用第二个版本(按值).为什么他们不提出const引用的内容(至少我没有找到任何直接的建议):

for (auto const &x : vec) // <-- see …
Run Code Online (Sandbox Code Playgroud)

c++ c++11

199
推荐指数
3
解决办法
8万
查看次数

为什么可以在for-statement中重新分配引用const?

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

vector<int> v = { 1,2 };
const int &r1 = v[0];
//r1 = v[1];  // compiler will show error.
Run Code Online (Sandbox Code Playgroud)

我知道r1无法重新分配引用const .但请看下面的代码:

for (const int &r2 : v) cout << r2;
Run Code Online (Sandbox Code Playgroud)

为什么不会出错?参考const r2分配了两次,对吧?

c++

30
推荐指数
3
解决办法
1116
查看次数

标签 统计

c++ ×2

c++11 ×1