【发布时间】:2018-11-08 21:42:21
【问题描述】:
所以对于我的部分作业,我需要制作一个 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;
}
}
目前我收到编译器错误提示
error: no match for ‘operator[]’(操作数类型是 ‘Player’ 和 'int') p[i].scoreBoard=updateScore(p[i], dice);
其他时候我尝试使用 p[i]
【问题讨论】:
-
'p' 应该是指向 Player 的指针。初始化它的行可能不应该编译。
-
Player p不是指针。请改用Player *p。 -
旁注:您的老师可能暂时将其列在“请勿使用”列表中,但请查看
std::vector。它解决了您在使用动态分配数组时会遇到的大部分问题。
标签: c++ arrays pointers reference