为什么下面的代码是非法的?
for (int index=0; index<3; index++)
{
cout << {123, 456, 789}[index];
}
虽然这很好用:
for (int value : {123, 456, 789})
{
cout << value;
}
IDEOne 中的代码:http: //ideone.com/tElw1w
为什么下面的代码是非法的?
for (int index=0; index<3; index++)
{
cout << {123, 456, 789}[index];
}
虽然这很好用:
for (int value : {123, 456, 789})
{
cout << value;
}
IDEOne 中的代码:http: //ideone.com/tElw1w
虽然std::initializer_list
不提供operator[]
,但它确实具有重载,begin()
并且end()
是基于范围的用途。实际上,您可以initializer_list
像这样索引:
for (int index=0; index<3; index++)
{
cout << begin({123, 456, 789})[index];
}
像花括号初始化列表一样{123, 456, 789}
本身没有类型,并且不能被索引(实际上也不能与大多数其他运算符一起使用)。
基于范围的for
循环对这种情况进行了特殊处理以使其工作。(从技术上讲,特殊处理是在auto&&
它内部使用的,它std::initializer_list
从一个花括号初始化列表中推断出 a 。)