以下代码节选自 C++ Primer 5th Ed.
string s("Hello World"); for (auto &c: s) c = toupper(c); cout << s << endl;
这里面有一个引用类型的变量c。在for循环遍历字符串的过程中,这个引用岂不是指向了不同的位置?不是说引用的指向不能改变吗?
c
for
光阴似箭催人老,日月如移越少年。
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
Just think that every time you loop, you will newly define a reference whose scope is limited to one loop:-)
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
Just think that every time you loop, you will newly define a reference whose scope is limited to one loop:-)