所以对于我的部分作业,我需要制作一个 yahtzee 风格的文字游戏。目前我正在研究一个数组来保存骰子值。我的问题是能够将数组传递给函数以修改值,然后再次使用修改后的数组。最初我想用引用或指针来做。我在这样做时遇到了问题,而且我无法通过任何一种方式进行编译。今天我和我的老师交谈,他告诉我数组可以在函数内部正常修改然后再次使用,本质上是说它们是通过引用自动传递的。
有人可以澄清一下我老师的意思以及是否正确。另外,你们会推荐什么方法。下面是我当前尝试使用引用的实现
/******************************************************
** Function: runGame
** Description: Runs game and keeps track of players
** Parameters: # of players
** Pre-Conditions: c is an integer from 1 to 9
** Post-Conditions:
******************************************************/
void runGame(int players) {
Player p = new Player[players]; //needs to be deleted at the end
int dice[] = { -1, -1, -1, -1, -1 };
int category; // used to hold category chosen
while (isGameOver(p)) {
for (int i = 0; i < players; i++) {
rollDice(dice); //uses reference
p[i].scoreBoard= updateScore(p[i], dice);
p[i].catsLeft--;
}
}
}
/******************************************************
** Function: rollDice
** Description: rolls dice, prints array and either rerolls
** Parameters: int[] dice
** Pre-Conditions:
** Post-Conditions:
******************************************************/
void rollDice(int (&dice) [5]) {
int again;
string indices; // indices of dice to reroll
cout << "Your dice are" << endl;
for (int i = 0; i < 5; i++) {
dice[i] = rand() % (6) + 1;
cout << dice[i];
}
for (int i = 0; i < 2; i++) {
cout << "Roll again? Type anything except 0 to go again." << endl;
cin >> again;
if (again) {
cout << "Type each index without a space that you would like to reroll";
cin.ignore();
getline(cin, indices);
for (int i = 0; i < indices.length(); i++) {
dice[(int)indices[i] - '0'] = rand() % (6) + 1;
}
}
else
break;
}
}
目前我收到编译器错误说
错误:'operator[]' 不匹配(操作数类型为 'Player' 和 'int') p[i].scoreBoard= updateScore(p[i], dice);
其他时间我尝试使用 p[i]