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

标签 c++ visual-studio codeblocks

<分区>

我是 C++ 新手,正在为类编写程序。该程序是两人之间的井字游戏。我已经完成了一个不使用函数的程序版本,我正在尝试使用它们。

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

这是代码;

// 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()

我该怎么做?

最佳答案

一个好的 C++ 类(class)应该在数组之前先介绍类。您在此处使用的数组类型是原始构建 block ,这就是您苦苦挣扎的原因。

我们在这里猜测您的类(class)已经涵盖的内容,但这是您通常的做法:

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

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

关于c++如何输出我在函数中操作的数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46588971/

相关文章:

visual-studio - 如何在安装 Visual Studio 2017 和 2019 后清理硬盘空间?

c++ - 更改标题栏图标时如何正确使用 LoadIcon 和 MAKEINTRESOURCE?

c++ - 对自定义控件使用类回调?

c++ - 在 C++ 中的类中定义结构

.net - 您能否将一段代码标记为仅包含在调试版本中?

c++ - 为什么同一编译器的不同版本会给出不同的结果?

c++ - 未定义对WinMain @ 16的引用和未知的编译指示

c++ - 如何将 boost::filesystem::directory_entry::path() 值分配给字符串?

c++ - CPP 中的单例

c# - 无法使用 Visual Studio 2017 制作我的程序的可执行文件