我正在尝试构建一个具有几种不同配置的数组,其中将随机选择一个配置。我首先尝试的代码是:
void createArray() {
int* tileVals;
int randInt = rand() % 3;
switch (randInt) {
case 0:
int tileVals[] = {1,1,1,2,2,2,3,3,3};
break;
case 1:
int tileVals[] = {1,1,1,1,2,2,3,3,3};
break;
case 2:
int tileVals[] = {1,1,1,1,2,2,2,3,3};
break;
}
// Do stuff with tileVals
}
但我得到了编译器错误:
src/Board.cpp:67:7: error: redefinition of 'tileVals'
int tileVals[] = {1,1,1,1,2,2,2,3,3};
src/Board.cpp:70:7: error: redefinition of 'tileVals'
int tileVals[] = {1,1,1,2,2,2,2,3,3};
...
我接下来尝试:
void createArray() {
int* tileVals;
int randInt = rand() % 3;
switch (randInt) {
case 0:
int case0[] = {1,1,1,2,2,2,3,3,3};
tileVals = case0;
break;
case 1:
int case1[] = {1,1,1,1,2,2,3,3,3};
tileVals = case1;
break;
case 2:
int case2[] = {1,1,1,1,2,2,2,3,3};
tileVals = case2;
break;
}
// Do stuff with tileVals
}
但这返回了编译器错误:
src/Board.cpp:85:2: error: switch case is in protected scope
case 6:
^
src/Board.cpp:82:7: note: jump bypasses variable initialization
int case5[] = {1,1,1,2,2,3,3,3,3};
...
我知道我可以通过在每个 case 语句中使用 for 循环来实现这一点,然后将值分配给在 switch 语句外部创建的tileVals 数组,但这似乎不是一种非常有效的方法。有没有更好的办法?谢谢。