因此,在我的一部分家庭作业,我需要做一个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’) pi.scoreBoard= updateScore(pi,骰子);
在其他时候,我尝试使用pi
发布于 2018-11-09 09:14:40
您的老师的意思是,您可以将数组作为指针传递给另一个函数,并使用它来修改另一个函数中数组中的值。使用下面的示例检查修改数组之前和修改后打印的值。注意数组是如何从主函数传递到modifyArray函数的。
#include "stdafx.h"
#include <iostream>
using namespace std;
void modifyArray(int * arr, int len)
{
for (int i = 0; i < len; i++)
{
arr[i] += 1;
}
}
void printArr(int *arr, int len)
{
for (int i = 0; i < len; i++)
{
cout << arr[i];
}
cout << endl;
}
int main()
{
int arr[5] = { 1,2,3,4,5 };
cout << "Before :" << endl;
printArr(arr, 5);
modifyArray(arr, 5);
cout << endl << "After : " << endl;
printArr(arr, 5);
return 0;
}发布于 2018-11-09 05:24:17
您的老师的意思是,如果您有一个带有缓冲区整数的指针,并且始终保存这些值。
例如:
int* p = new int[5];这将创建一个包含5个时隙的数组,每次填充它时,总是会发生变化,如果您是面向对象的,那么有些事情可能会有所不同,但大多数情况都是这样的。您可以使用is作为测试的全局变量。
你能移动它的方式是写你想要的两个pslot数字。这种方式将使您可以使用数组,另一种方法是返回带有数字的数组(而不是空的)。
https://stackoverflow.com/questions/53216580
复制相似问题