C ++的新手,制作一个tic tac toe游戏,我的阵列似乎是打印乱码,如下面的输出部分所示。我如何制作它以便我可以用char'填充数组'。'?使用c ++ 11
的main.cpp
#include <iostream>
#include "Board.hpp"
//to determine win condition:
//check row
//check column
//check diagonal
//else it's a draw
int main() {
Board board1;
board1.print();
board1.makeMove(0,0,'x');
board1.print();
if(board1.makeMove(0,0,'x'))
std::cout<<"true"<<std::endl;
else
std::cout<<"false"<<std::endl;
std::cout<<"finished!"<<std::endl;
}
Board.hpp
#ifndef BOARD_HPP
#define BOARD_HPP
class Board {
private:
char grid[3][3];
public:
Board();
int makeMove(int xIn, int yIn,char playerTurnIn);
void print();
};
#endif //UNTITLED_BOARD_HPP
Board.cpp
#include "Board.hpp"
#include <iostream>
/*default constructor which initializes an empty array with .*/
Board::Board() {
char grid[3][3] = {{'.','.','.'},{'.','.','.'},{'.','.','.'}};
}
/*declare this in the board class
make sure to add Board:: for makeMove and print functions*/
int Board::makeMove(int xIn, int yIn,char playerTurnIn) {
if (grid[xIn][yIn]=='.') {
grid[xIn][yIn] = playerTurnIn;
return true;
}
else {
return false;
}
}
void Board::print() {
std::cout<<" 0 1 2"<<std::endl;
for (int row = 0; row < 3; row++) {
std::cout<<row<<' ';
for (int col = 0; col < 3; col++) {
std::cout<<grid[row][col]<<' ';
}
std::cout<<std::endl;
}
}
输出:
0 1 2
0 d 1(╗
2∟@ 0 1 2
0 d 1(╗
2∟@
假
完成!
答案 0 :(得分:5)
问题出在你的构造函数中:
Board::Board() {
char grid[3][3] = {{'.','.','.'},{'.','.','.'},{'.','.','.'}};
}
在那里,您要声明并初始化 new 数组。
请改为尝试:
Board::Board() : grid{{'.','.','.'},{'.','.','.'},{'.','.','.'}} {}
在Ideone上测试。谢谢@Scheff