0

所以对于我的部分作业,我需要制作一个 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]

4

2 回答 2

1

您的老师的意思是您可以将数组作为指针传递给另一个函数,并使用它来修改另一个函数中数组内的值。使用以下示例检查修改数组之前和修改后打印的值。注意数组是如何从 main 函数传递到 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-09T09:14:40.337 回答
0

你的老师的意思是,如果你有一个带有缓冲区整数的指针,并且它总是保存值。

前任:

int* p = new int[5];

这将创建一个有 5 个插槽的数组,现在每次填充它时它总是会改变,如果你正在做面向对象的事情,有些事情可能会有点不同,但大多数情况下会是这样。您可以使用 is 作为全局变量进行测试。

你可以移动它的方法是写 p[你想要的插槽号]。这种方式将使您可以使用数组,另一种方式是返回带有数字的数组(而不是 void)。

于 2018-11-09T05:24:17.107 回答