【发布时间】:2016-03-26 19:42:51
【问题描述】:
我正在尝试使用类创建经典的井字游戏。我通过默认构造函数建立了我的数组,当我尝试从类中的另一个公共函数显示游戏板时,我得到了像这些'&♥'这样的随机符号。 (我知道我缺少功能,但我无法弄清楚这一步!)这是我的程序输出:OUTPUT 和程序:
class TicTacToe
{
private:
char board[3][3];
char player;
public:
void getBoard();
char changePlayer(char);
void setPosition(int, int);
TicTacToe();
};
int main ()
{
bool endOfGame = false;
int rows;
int columns;
int test;
TicTacToe ttt;
while (!endOfGame)
{
cout << "Please enter the row number: ";
cin >> rows;
cout << "Please enter the column number: ";
cin >> columns;
ttt.setPosition(rows, columns);
ttt.getBoard();
}
return 0;
}
TicTacToe::TicTacToe()
{
char board[3][3] = {'*','*','*',
'*','*','*',
'*','*','*',};
player = 'x';
}
void TicTacToe::getBoard()
{
for (int i = 0; i < 3; i++)
{
for (int c = 0; c < 3; c++)
{
cout << board[i][c];
}
cout << endl;
}
}
char TicTacToe::changePlayer(char choice)
{
}
void TicTacToe::setPosition(int row, int column)
{
if (player == 'x')
{ board[row][column] = 'x'; }
else
{ board[row][column] = 'o'; }
}
【问题讨论】:
-
除非我遗漏了什么,否则您永远不会初始化数组,因此它将指向您要解释为字符的垃圾数据。
-
在main中,当我将ttt声明为tictactoe时,不会声明一个游戏板,使默认构造函数使其成为3x3数组吗?