c ++如何输出一个我在函数中操作的数组?

时间:2017-10-05 15:06:08

标签: c++ visual-studio codeblocks

我是C ++的新手,我正在上课。该计划是两人之间的Tic Tac Toe游戏。我已经完成了一个不使用函数的程序版本,我试图利用它们。

我想编辑一个函数中的数组并输出稍后在程序中使用的函数。

这是代码;

// This is a assessment project which plays ticTacToe between two players.

#include <iostream>

using namespace std;

int main() {

    void displayBoard(char ticTacToeGame[][3]); // sets up use of displayBoard()
    char userPlay(); // sets up use of userPlay()
    char addplayToBoard(char play, char ticTacToeGame[][3] ); // sets up use of addPlayToBoard()


    char ticTacToeGame[3][3] = {'1', '2', '3', '4', '5', '6', '7', '8', '9'}; // game board array


    // declaration of variables
    char play;

    displayBoard(ticTacToeGame); // displays the board to user
    play = userPlay(); // gets users play and stores it as a char

    return 0;
} // end of main()

// function used to display the board
void displayBoard(char ticTacToeGame[][3]) {

    // display board
    for (int row = 0; row < 3; row++) {

        cout << endl;

        for (int column = 0; column < 3; column++) {
            cout << "| " << ticTacToeGame[row][column] << " ";
        }

        cout << "|\n";

        if (row < 2) {
            for (int i = 0; i < 19; i++) {
                cout << "-";
            }
        }
    }


} // end of displayBoard()

// function used to get users play
char userPlay() {

    // declaration of variables
    char play;

    cout << "Play: ";
    cin >> play;
    cout << endl;

    return play;

} // end of userPlay()

// function used to add users play to board
char addPlayToBoard(char play, char ticTacToeGame[][3]) {

    for (int row = 0; row < 3; row++) {
        for (int column = 0; column < 3; column++) {
            if (ticTacToeGame[row][column] == play){
                ticTacToeGame[row][column] = 'O';
            }
        }
    }
    return ticTacToeGame;

} // end of addPlayToBoard()

我该怎么做?

1 个答案:

答案 0 :(得分:2)

一个好的C ++课程将涵盖数组之前的类。你在这里使用的那种阵列是一个原始的构建块,这就是你在苦苦挣扎的原因。

我们在这里猜测你的课程已经涵盖了一些内容,但这就是你通常的做法:

class Board {
   char fields[3][3];
public:
   // Class methods
};

以下是重要原因:C ++类是完整的类型,可以从函数返回,就像int值一样。但通常甚至不需要:类方法在该类上就地工作。