目前正在讀 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呢
謝謝