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)
如果不使用引用,那么代码在逻辑上将类似于
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 语句同样有效。