for 循环中的 C++ 参考

Liu*_*Hao 5 c++ loops for-loop reference

正如下面代码的for循环中一样,为什么我们必须使用reference( &c)来改变c. 为什么我们不能只在循环c中使用for。也许这是关于参数和参数之间的区别?

#include "stdafx.h"
#include<iostream>
#include<string>

using std::string;
using std::cout;
using std::cin;
using std::endl;
int main()
{
    string s1("Hello");
        for (auto &c : s1)
            c = toupper(c);
            cout << s1 << endl;
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

Mac*_*bły 7

的情况下:

对于(自动 cCpy:s1)

cCpy 是当前位置字符的副本。

的情况下:

for (自动 &cRef : s1)

cRef 是对当前位置字符的引用。

它与参数和参数无关。它们连接到函数调用(您可以在这里阅读:“参数”与“参数”)。


Vla*_*cow 3

如果不使用引用,那么代码在逻辑上将类似于

for ( size_t i = 0; i < s1.size(); i++ )
{
    char c = s1[i];
    c = toupper( c );
}
Run Code Online (Sandbox Code Playgroud)

也就是说,每次在循环内都会有更改的对象c获取 的副本s1[i]s1[i]本身不会改变。但是如果你会写

for ( size_t i = 0; i < s1.size(); i++ )
{
    char &c = s1[i];
    c = toupper( c );
}
Run Code Online (Sandbox Code Playgroud)

then 在这种情况下 as是对when语句的c引用s1[i]

    c = toupper( c );
Run Code Online (Sandbox Code Playgroud)

改变s1[i]自己。

这对于基于范围的 for 语句同样有效。