【发布时间】:2016-05-16 01:04:25
【问题描述】:
所有。我有一个类定义如下:
class Board {
int columns, rows;
bool board[10][10];
public:
Board(int, int);
void nextFrame();
void printFrame();
};
我的void nextFrame() 不断给我[rows][columns] 的错误,因为“'this' 不能在常量表达式中”对于他们两个。我该如何重新定义它以使其正常工作?我理解错误。函数定义如下,错误出现在下面代码示例的第3行。
void Board::nextFrame() {
int numSurrounding = 0;
bool tempBoard[rows][columns];
for (int i = 0; i < rows; i++)
{
for (int j = 0; j < columns; j++)
{
if ((i + 1) < rows && board[i + 1][j] == true)
{
numSurrounding++;
}
if ((i - 1) >= 0 && board[i - 1][j] == true)
{
numSurrounding++;
}
if ((j + 1) < columns && board[i][j + 1] == true)
{
numSurrounding++;
}
if ((j - 1) >= 0 && board[i][j - 1] == true)
{
numSurrounding++;
}
if ((i + 1) < rows && (j + 1) < columns && board[i + 1][j + 1] == true)
{
numSurrounding++;
}
if ((i + 1) < rows && (j - 1) >= 0 && board[i + 1][j - 1] == true)
{
numSurrounding++;
}
if ((i - 1) >= 0 && (j + 1) < columns && board[i - 1][j + 1] == true)
{
numSurrounding++;
}
if ((i - 1) >= 0 && (j - 1) >= 0 && board[i - 1][j - 1] == true)
{
numSurrounding++;
}
if (numSurrounding < 2 || numSurrounding > 3)
{
tempBoard[i][j] = false;
}
else if (numSurrounding == 2)
{
tempBoard[i][j] = board[i][j];
}
else if (numSurrounding == 3)
{
tempBoard[i][j] = true;
}
numSurrounding = 0;
}
}
for (int i = 0; i < rows; i++)
{
for (int j = 0; j < columns; j++)
{
board[i][j] = tempBoard[i][j];
}
}
}
【问题讨论】:
-
bool tempBoard[rows][columns];-- 这不是有效的 C++ 语法。声明条目数时,数组必须使用编译时常量。 -
bool tempBoard[rows][columns];是一个可变长度数组。数组的维度必须是常量表达式。除非您的对象(类,this)也是编译时常量,否则情况并非如此。但是,如果this是const,那么就不能修改board... -
@PaulMcKenzie 而不是写“Board TempBoard”?
-
@yeawhadavit - 使用
std::vector<std::vector<bool>> tempBoard(rows, std::vector<bool>(columns)); -
谢谢@PaulMcKenzie!
标签: c++ error-handling