4
全部。我有一個類定義如下:'this'不能用於常量表達式錯誤(C++)
class Board {
int columns, rows;
bool board[10][10];
public:
Board(int, int);
void nextFrame();
void printFrame();
};
我void nextFrame()
不斷給我的錯誤,因爲[rows][columns]
「‘這個’不能在一個常量表達式」對他們倆的。我怎樣才能重新定義這個,以便它工作?我明白錯誤。該函數的定義如下,並且錯誤發生在以下代碼示例的第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++語法。聲明條目數時,數組必須使用編譯時常量。 – PaulMcKenzie
'bool tempBoard [rows] [columns];'是一個可變長度的數組。數組的維度必須是常量表達式。除非你的對象(class,'this')也是一個編譯時常量,否則情況就不一樣了。然而,如果'this'是'const',那麼你不能修改'board' ... – user6338625
@PaulMcKenzie而不是寫「Board TempBoard」? – yeawhadavit