在构造函数中初始化2D数组

时间:2018-04-20 22:47:55

标签: c++

长话短说我试图将我的2D数组的所有值初始化为构造函数中的空白。我知道我可以创建一个for循环来填充数组但是我想知道你是否可以使用指针或引用填充它,这是我认为你必须做的但是我目前还没有理解这样做一件事。

class TicTacToe {

// state of the game
char M[3][3];
int numRemainingChoices; // number of remaining choices
char turn; // to determine whose turn it is

public:

TicTacToe(char array[][3]) {
// initializes each cell of M to a blank, sets turn to X, and 
numRemainingChoices to 9
M[][] = {{" ", " ", " "}, {" ", " ", " "}, {" ", " ", " "}};
turn = 'x';
numRemainingChoices = 9;
// Then calls runTicTacToe()
runTicTacToe();
}

具体来说,我想用"填充2D数组M. "但我需要在构造函数中这样做。我尝试将2D数组作为参数添加,然后像我在代码中一样填充它。当我尝试这个时,我得到一个错误陈述:"标量初始化器中的多余元素"。我不完全理解这是否只是创建数组的副本并填充它或者是否用空白填充原始数组。如果有人能够澄清并向我解释幕后发生的事情,那将是一个很大的帮助。

1 个答案:

答案 0 :(得分:2)

首先," "字符串(出于实际目的可以看作是char const*),并且您有char的数组。< / p>

要继续这不是初始化数组的方式,您不能分配给它。

而是使用构造函数初始化列表,如

TicTacToe()
    : M{{' ', ' ', ' ' }, {' ', ' ', ' ' }, {' ', ' ', ' ' }},
      numRemainingChoices(9), turn('x')
{
    // As little as possible here
    // ...
}

如评论所述,不要在构造函数中“运行”任何内容。构造函数应初始化新对象的状态,。如果你想“运行”任何东西,那么一旦构造了对象就去做:

TicTacToe gameObject;  // Create and initialize the object
gameObject.run();  // Start the game
相关问题