[英]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.