使用类

时间:2016-03-26 19:42:51

标签: c++ arrays

我试图用类创建一个经典的tic tac toe游戏。我通过默认构造函数建立了我的数组,当我尝试从类中的另一个公共函数显示游戏板时,我会得到像这样的随机符号'&♥'。 (我知道我缺少功能,除了我无法解决这个问题!)这是我的程序输出: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'; }

}
&#13;
&#13;
&#13;

2 个答案:

答案 0 :(得分:0)

您永远不会初始化您的类成员数组。构造函数中的数组是本地对象。一个简单的解决方案是使用类内初始化器并删除构造函数:

class TicTacToe
{
    private:
        char board[3][3] {'*','*','*','*','*','*','*','*','*'};
        char player {'x'};

    public:
        void getBoard();
        char changePlayer(char);
        void setPosition(int, int);
};

编辑,当你需要一个构造函数时使用初始化列表(从c ++ 11开始):

TicTacToe::TicTacToe()
    : board {'*', '*', '*', '*', '*', '*', '*', '*', '*'}
{}

答案 1 :(得分:0)

解决方案:

TicTacToe::TicTacToe()
{
	for (int i = 0; i < 3; i++)
	{
		for (int c = 0; c < 3; c++)
		{
			board[i][c] = '*';
		}
	cout << endl;
	}
	
	player = 'x';
}

void TicTacToe::getBoard()
{	
	cout << "\n" << board[0][0] << " | " << board[0][1] << " | " << board[0][2];
	cout << "\n" << "---------";
	cout << "\n" << board[1][0] << " | " << board[1][1] << " | " << board[1][2];
	cout << "\n" << "---------";
	cout << "\n" << board[2][0] << " | " << board[2][1] << " | " << board[2][2];
	cout << endl << endl;

}