我正在尝试学习 C++,但尽管花了很多时间寻找答案,但我还是无法理解这里的代码:
#include <iostream>
void printArray1(int (&array)[3]) {
for(int x : array)
std::cout << x << " ";
}
void printArray2(int array[]) {
for(int x : array) // compiler error, can't find begin and end
std::cout << x << " ";
}
int main() {
int a[3] = {34,12,88};
for(int x : a)
std::cout << x << " ";
std::cout << std::endl;
printArray1(a);
printArray2(a);
std::cout << std::endl;
return 0;
}
Run Code Online (Sandbox Code Playgroud)
在printArray1 中,我们接收到一个参数,该参数是对大小为3 的数组的引用。这是否意味着我们正在接收整个数组的地址,还是只接收到大小为3 的数组中第一个元素的地址?另外,这个参数是如何传递给循环的?
在printArray2 中,我们接收到一个指向数组中第一个元素的指针,对吗?换句话说,我们也收到了一个地址,就像在 printArray1 中一样?因此,此函数中基于范围的 for 循环将无法编译,因为我们没有数组的大小数据,对吗? …