[英]Passing an array to a function to display a tic-tac-toe board
我正在尝试为一项家庭作业项目创建一个井字游戏,但是我一直不知道如何传递数组。 目前,我有这个:
原型:
void displayBoard(char);
变量:
const int COLS = 3;
const int ROWS = 3;
char board[ROWS][COLS] = {'*', '*', '*', '*', '*', '*', '*', '*', '*'};
函数调用:
displayBoard(board);
功能:
void displayBoard(char board)
{
//DISPLAYBOARD displayBoard shows the current tic-tac-toe board
//along with proper spacing
cout << "---------------------" << endl << endl;
cout << " | | " << endl;
cout << " " << board[0][0] << " | " << board[0][1] << " | " << board[0][2] << endl;
cout << "_____|_____|_____" << endl;
cout << " | | " << endl;
cout << " " << board[1][0] << " | " << board[1][1] << " | " << board[1][2] << endl;
cout << "_____|_____|_____" << endl;
cout << " | | " << endl;
cout << " " << board[2][0] << " | " << board[2][1] << " | " << board[2][2] << endl;
cout << " | | " << endl;
}
我尝试了将多维数组传递给函数displayBoard的几种变体,但我不断遇到诸如此类的错误:
'void displayBoard(char)'无法将参数1从'char [3] [3]'转换为'char',如果我将括号()留空,我还会收到一条错误消息,提示“板未初始化” t,并且我不想使用全局变量。
原型应该是直觉的:
void displayBoard(const char (&board)[ROWS][COLS]);
使用std::array<std::array<char, 3u>, 3u>
将具有更直观的语法。
如果需要显示不同大小的板,则可以将模板用于displayBoard方法:
template <int SizeX, int SizeY>
void displayBoard(const char (&board)[SizeX][SizeY])
{
cout << "---------------------" << endl << endl;
cout << " | | " << endl;
cout << " " << board[0][0] << " | " << board[0][1] << " | " << board[0][2] << endl;
cout << "_____|_____|_____" << endl;
cout << " | | " << endl;
cout << " " << board[1][0] << " | " << board[1][1] << " | " << board[1][2] << endl;
cout << "_____|_____|_____" << endl;
cout << " | | " << endl;
cout << " " << board[2][0] << " | " << board[2][1] << " | " << board[2][2] << endl;
cout << " | | " << endl;
}
但是要小心,并始终检查是否正在访问数组中的现有索引
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.