目前正在读 C++ Primer 5th edition
int ia[3][4] = {{0,1,2,3},{4,5,6,7},{8,9,10,11}};
for(auto row : ia)
for(auto col : row)
cout<< col <<endl;
这样子compile是不会过的
外层循环的row必须要是reference才行,也就是 &row
书上的理由如下:
Because row is not a reference, when the compiler initializes row it will
convert each array element (like any other object of array type) to a pointer
to that array's first element. As a result, in this loop the type of row is
int*, The inner for loop is illegal. Despite our intentions, that loop
attempts to iterate over an int* .
reference不就是让一个变量有了另一个名称,并且这两个名称都使用同一块内存
位址吗?
为什么有reference的话,each array element就不会被转换成指向第一个元素的指标?
请问为什么row要reference呢
谢谢