作者热门文章
- c - 在位数组中找到第一个零
- linux - Unix 显示有关匹配两种模式之一的文件的信息
- 正则表达式替换多个文件
- linux - 隐藏来自 xtrace 的命令
我是 C++ 的新手,正在尝试学习关键字“auto”和引用的概念。我在网上看到这个问答。
Is the following range for legal? If so, what is the type of c?
const string s = "Keep out!";
for (auto &c : s){ /*... */ }
答案是:
Depending on the code within for loop body. For example:
cout << c; // legal.
c = 'X'; // illegal.
没有提供任何解释。有人可以解释为什么会这样吗?
最佳答案
因为字符串是常量,所以您不能修改它。基于范围的循环使用 auto &
类型,它将有效地变为 const char &
。这意味着您引用的是实际字符串中的字符,而不是它们的拷贝。
关于c++ - 在下面代码的上下文中,为什么 "cout << c"合法而 "c = "x""非法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35145514/
我是一名优秀的程序员,十分优秀!