相关疑难解决方法(0)

基于范围的for-loop on数组传递给非主函数

当我尝试在gcc 4.8.2中编译以下代码时,我收到以下错误:

test.cc: In function ‘void foo(int*)’:
test.cc:15:16: error: no matching function for call to ‘begin(int*&)’
   for (int i : bar) {
                ^
Run Code Online (Sandbox Code Playgroud)

与模板库中更深层次的其他一些人一起.

#include <iostream>
using namespace std;

void foo(int*);

int main() {
  int bar[3] = {1,2,3};
  for (int i : bar) {
    cout << i << endl;
  }
  foo(bar);
}

void foo(int* bar) {
  for (int i : bar) {
    cout << i << endl;
  }
}
Run Code Online (Sandbox Code Playgroud)

如果我重新定义foo使用索引for循环,那么代码将按预期编译和运行.此外,如果我将基于范围的输出循环移动到main,我也会得到预期的行为.

如何barfoo一种能够在其上执行基于范围的for循环的方式传递数组?

c++ gcc for-loop c++11

9
推荐指数
2
解决办法
2398
查看次数

标签 统计

c++ ×1

c++11 ×1

for-loop ×1

gcc ×1