为什么当数组作为调用方函数中的参数传递时,不能在被调用函数中使用 foreach 循环打印数组的值
Why values of array cannot be printed using foreach loop in called function when array is passed as argument in caller function?
我正在尝试使用 foreach 循环在调用函数中打印数组的值,但遇到编译错误。在 Linux 平台中使用 c++11 编译器并使用 VIM 编辑器。
尝试使用 C 样式 for 循环并且当大小从调用函数传递时,它起作用了
#include <iostream>
using namespace std;
void call(int [], int);
int main()
{
int arr[] = {1,2,3,4,5};
int size = sizeof(arr)/sizeof(arr[0]);
call(arr,size);
}
void call(int a[],int size)
{
for(int i =0 ; i<size; i++)
cout << a[i];
}
以下代码中使用的 for-each 循环,编译失败。
#include <iostream>
using namespace std;
void call(int []);
int main()
{
int arr[] = {1,2,3,4,5};
call(arr);
}
void call(int a[])
{
for ( int x : a )
cout << x << endl;
}
对于 C++11 中的每个循环都希望知道要迭代的数组的大小?如果是这样,它将如何帮助传统的 for 循环。还是我在这里编码的错误?
我期待着你的帮助。提前谢谢。
因为int a[]
作为函数参数不是数组,所以它与写int *a
相同。
您可以通过引用传递数组以使其工作:
template <size_t N> void call(int (&a)[N])
工作示例:https://ideone.com/ZlEMHC
template <size_t N> void call(int (&a)[N])
{
for ( int x : a )
cout << x << endl;
}
int main()
{
int arr[] = {1,2,3,4,5};
call(arr);
}
相关文章:
- 函数调用中参数的顺序重要吗
- 基于另一个成员参数将函数调用从类传递给它的一个成员
- 变量没有改变?通过向量的函数调用
- 在两个类中共享相同的函数调用,并在不需要时避免空实例化
- 是否有C++编译器选项允许激进地删除所有函数调用,并将参数传递给具有空体的函数
- 我知道函数调用中存在歧义.有没有办法调用foo()函数
- 模板函数调用
- 获取从C++中同一类中的构造函数调用的方法返回的值
- 析构函数调用
- 成员函数调用和C++对象模型
- 使用共享指针的函数调用,其对象应为 const
- C++:编译时检查匹配的函数调用对?
- 函数调用C++中的参数太少
- 来自 DLL 的函数调用 [表观调用的括号前面的表达式必须具有(指向-)函数类型]
- 返回指向对象的指针的函数调用是否为 prvalue?
- C++ 如何重载 [] 运算符并进行函数调用
- 代码的效率. 转到和函数调用
- 是同一作用域的函数部分中的函数调用
- 如何封装一个函数,以便它只能由同一类中的一个其他函数调用?
- 类型擦除的std::function与虚拟函数调用的开销