search

Home  >  Q&A  >  body text

c++11 - C++ 11的range for里面定义的引用,为什么能被修改?

以下代码节选自 C++ Primer 5th Ed.

string s("Hello World");
for (auto &c: s)
    c = toupper(c);
cout << s << endl;

这里面有一个引用类型的变量c
for循环遍历字符串的过程中,这个引用岂不是指向了不同的位置?
不是说引用的指向不能改变吗?

大家讲道理大家讲道理2803 days ago873

reply all(2)I'll reply

  • 大家讲道理

    大家讲道理2017-04-17 13:02:24

    The c here is an alias of a variable (iterator). What you are changing is that the content pointed to by c is not a reference

    reply
    0
  • 天蓬老师

    天蓬老师2017-04-17 13:02:24

    Just think that every time you loop, you will newly define a reference whose scope is limited to one loop:-)

    reply
    0
  • Cancelreply