gpt4 book ai didi

c++ - 在基于范围的 for 循环中重新声明变量

转载 作者:太空狗 更新时间:2023-10-29 20:40:20 24 4
gpt4 key购买 nike

此代码在 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: error: redeclaration of ‘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 i = *__begin;
{
std::string i = "oups";
}
}
}

因此内部 i 应该简单地隐藏循环控制 i 而不会出现任何问题。

并且,像这样 live example表明,当像这样拼写时,GCC 实际上接受它就好了。

关于c++ - 在基于范围的 for 循环中重新声明变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24526131/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com