'this'不能用于常量表达式错误 (C++)
'this' cannot be used in a constant expression error (C++)
all。我有一个类定义如下:
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];
}
}
}
您需要使用STL中的集合。
下面是一个嵌套矢量以获得棋盘的例子:
#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;
}
您可以在此处和此处了解board(vector<vector<bool>>(x, vector<bool>(y)))
的成员初始化语法。
相关文章:
- 警告处理为错误这里有什么问题
- "error: no matching function for call to"构造函数错误
- boost::进程间消息队列引发错误
- C++,OpenCV,尝试显示图像时"OpenCV(4.3.0) Error: Assertion failed (size.width>0 && size.height>0)"此错误
- 有关插入适配器的错误。[错误]请求从 'back_insert_iterator<vector<>>' 类型转换为非标量类型
- QT在错误的班级中寻找空位
- vector.resize()中的分配错误
- 代码在main()中运行,但在函数中出现错误
- 释放错误后堆使用
- (C++)分析树以计算返回错误值的简单算术表达式
- Project Euler问题4的错误解决方案
- 我的字符计数代码计算错误.为什么
- 从"int*"强制转换为"unsigned int"会丢失精度错误
- 尝试导入pybind-opencv模块时出现libgtk错误
- CMake项目Boost库错误:Boost/config/compiler/gcc.hpp:165:10:致命错误:cs
- 在某些循环内使用vector.push_back时出现分段错误
- MSVC多行宏编译器错误
- 静态数据成员的问题-修复链接错误会导致编译器错误
- 为什么在运行时没有向我们提供有关分段错误的更多信息?
- 错误:未在此范围内声明'reverse'