我希望在C++中的switch/case语句中使用一个const int数组,这是否可能?到目前为止,我尝试了以下内容:
然而编译器不断告诉我:
我将我的数组声明为 "int const",这不足够吗?
int main()
{
int const tab[3] = {1,2,3};
int value(2);
switch(value)
{
case tab[1]:
cout << "result is: " << tab[0]<< endl;
}
return 0;
}
然而编译器不断告诉我:
.../main.cpp|11|error: the value of ‘tab’ is not usable in a constant expression
我将我的数组声明为 "int const",这不足够吗?
tab
不是整数或枚举类型。如果它是const int tab = 1;
,你可以使用case tab
。 - Barrytab
而不是tab[1]
? - David Gtab[1]
是整数类型并不足够,因为评估子表达式tab
仍需要一个rvalue转换,并且抽象机器必须评估tab
以便评估tab[1]
。 - Steve Jessop