为什么下面的代码是非法的?
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
有成员begin
和end
,但没有operator[]
。 - clcto{123, 456, 789}
不是一种类型,也不是表达式 - 更进一步地说,decltype({1, 2, 3})
被定义为不合法。一个例外是使用auto
进行类型推导。 - HelloWorld