在基于范围for循环中重新声明变量 [英] Redeclaration of variable in range-based for loops

查看:197
本文介绍了在基于范围for循环中重新声明变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

此代码在GCC 4.8.1中失败,但可与MSVC2013一起使用:

  #include< vector> 
#include< string>

int main()
{
std :: vector< int> V {1,2,3,4,5};

for(auto i:V)
{
std :: string i =oups;




GCC 4.8.1讲述:

  prog.cpp:10:17:错误:重新声明'std :: string i'
std :: string i =oups;
$

是MSVC 2013编译器中的一些错误吗?

解决方案

是的,这是一个错误,但在GCC中。 C ++ 11 [stmt.ranged]清楚地表明,基于范围的 for 循环与此相当:

  {
auto&& __range =(V);
for(auto __begin = __range.begin(),
__end = __range.end();
__begin!= __end;
++ __ begin){
auto我= * __开始;
{
std :: string i =oups;





$ b

所以内部 i 应该简单地隐藏循环控制 i 而没有任何问题。



而且,正如本现场示例所显示的,当这样阐述时,GCC实际上接受它就好了。


This code fails with GCC 4.8.1 but works with MSVC2013:

#include <vector>
#include <string>

int main()
{
  std::vector<int> V{1,2,3,4,5};

  for (auto i : V)
  {
    std::string i = "oups";
  }
}

GCC 4.8.1 tells:

prog.cpp:10:17: error: redeclaration of ‘std::string i’
     std::string i = "oups";
                 ^

Is it some bug in the MSVC 2013 compiler?

解决方案

Yes, it's a bug, but in GCC. C++11[stmt.ranged] clearly states that your range-based for loop is equivalent to this:

{
  auto && __range = (V);
  for ( auto __begin = __range.begin(),
             __end = __range.end();
        __begin != __end;
        ++__begin ) {
    auto i = *__begin;
    {
      std::string i = "oups";
    }
  }
}

So the inner i should simply hide the loop-control i without any problems.

And, as this live example shows, when spelled out like this, GCC actually accepts it just fine.

这篇关于在基于范围for循环中重新声明变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆