gpt4 book ai didi

c++ - 在下面代码的上下文中,为什么 "cout << c"合法而 "c = "x""非法?

转载 作者:太空狗 更新时间:2023-10-29 20:02:48 25 4
gpt4 key购买 nike

我是 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com