C++ 'iter' 的名称查找更改为新的 ISO 'for' 范围
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3601154/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
name lookup of 'iter' changed for new ISO 'for' scoping
提问by Luis
I'm trying to compile the two files below, but get an error message from the compiler: gcc 4.3.3 (Linux)
我正在尝试编译下面的两个文件,但从编译器收到一条错误消息:gcc 4.3.3 (Linux)
The error is in the line signed with: LINE WITH ERROR
错误在签名的行中:LINE WITH ERROR
What I'm I doing wrong, how should I change it?
我做错了什么,我应该如何改变它?
Luis ...............................
路易斯 .....................................
$ g++ -c b.h b.cpp
b.cpp: In function 'void calcularDesempPop(std::vector<Individuo, std::allocator<Individuo> >&)':
b.cpp:19: error: name lookup of 'iter' changed for new ISO 'for' scoping
b.cpp:17: error: using obsolete binding at 'iter'
............................... FILE: b.cpp
..................... 文件:b.cpp
#include <iostream>
#include <algorithm>
#include "desempenho.h"
using std::cout;
using std::endl;
struct Individuo {
vector<double> vec;
double desempenho;
};
void calcularDesempPop(vector<Individuo>& pop) {
for (vector<Individuo>::iterator iter = pop.begin();
iter != pop.end(); ++iter);//LINE WITH ERROR
iter->desempenho = calcularDesempenho(iter->vec);
cout << endl;
}
............................... FILE: b.h
..................... 文件:bh
#ifndef GUARD_populacao_h
#define GUARD_populacao_h
//#include <algorithm>
#include <iostream>
#include "cromossoma.h"
struct Individuo {
vector<double> vec;
double desempenho;
};
void calcularDesempPop(vector<Individuo>& pop);
#endif
回答by Chubsdad
$6.5.3/3 - "If the for-init-statement is a declaration, the scope of the name(s) declared extends to the end of the for statement."
$6.5.3/3 - “如果 for-init-statement 是一个声明,则声明的名称的范围将扩展到 for 语句的末尾。”
Therefore iter cannot be accessed outside the for loop scope. Check the semicolon immediately after the for loop. Most probably you did not intend it that way.
因此不能在 for 循环范围之外访问 iter。在 for 循环之后立即检查分号。很可能你并不打算那样做。
回答by Cubbi
You left a semicolonafter for():
你在 for() 之后留下了一个分号:
for (vector::iterator iter = pop.begin(); iter != pop.end(); ++iter);
which means the next line is not a part of the loop body, and iter
is undefined in it.
这意味着下一行不是循环体的一部分,并且iter
在其中未定义。
回答by stefaanv
always avoid
总是避免
for(..;..;..); { }