'this'不能用于常量表达式错误(C++)
问题描述:
全部。我有一个类定义如下:'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];
}
}
}
答
您需要使用STL的集合。
下面是嵌套向量,让您的主板为例:您可以了解成员初始化语法board(vector<vector<bool>>(x, vector<bool>(y)))
here和here
#include <vector>
#include <iostream>
using namespace std;
class Board {
int columns, rows;
vector<vector<bool>> board;
public:
Board(int x, int y) : board(vector<vector<bool>>(x, vector<bool>(y))) {
}
void nextFrame() {
// Fill in
}
void printFrame() {
// Fill in
}
size_t xdim() {
return board.size();
}
size_t ydim() {
if (board.size() == 0) {
return 0;
}
return board.at(0).size();
}
};
int main() {
Board b(10, 20);
cout << "Made the board" << endl;
cout << "X: " << b.xdim() << endl;
cout << "Y: " << b.ydim() << endl;
}
。
'bool tempBoard [rows] [columns];' - 这是无效的C++语法。声明条目数时,数组必须使用编译时常量。 – PaulMcKenzie
'bool tempBoard [rows] [columns];'是一个可变长度的数组。数组的维度必须是常量表达式。除非你的对象(class,'this')也是一个编译时常量,否则情况就不一样了。然而,如果'this'是'const',那么你不能修改'board' ... – user6338625
@PaulMcKenzie而不是写“Board TempBoard”? – yeawhadavit