我正在尝试编译这段代码:
class OthelloState {
public: // constructor
Othello(int r, int c);
/* other stuff */
private: // private data
const int rows;
const int columns;
int board[rows][columns];
}
我一直以:
OthelloState.h:109: error: invalid use of non-static data member 'OthelloState::rows'
OthelloState.h:115: error: from this location
OthelloState.h:115: error: array bound is not an integer constant
OthelloState.h:112: error: invalid use of non-static data member 'OthelloState::columns'
OthelloState.h:115: error: from this location
OthelloState.h:115: error: array bound is not an integer constant
我假设这意味着我必须将行
和列
设为静态。但是,如果我将它们设置为静态,则我无法使用构造函数进行初始化,这是我在该项目中必须采用的方式...
还有其他方法吗?
PS:我知道在真正的奥赛罗游戏中,棋盘是一个 8 x 8 的正方形网格......但是考虑到计算机需要多长时间才能在部分 8 x 8 网格上生成下一个最佳着法,我们是不会玩“真正的”奥赛罗棋盘(即没有预定义的棋盘尺寸)。
最佳答案
在 C++ 中,可变长度数组是不允许的。 board[][]
需要在编译时知道它的两个维度。您可以使用 vector<vector<int> > board;
, 如果你想初始化 row
和 col
在运行时。
class OthelloState {
public:
OthelloState(int r, int c);
private: // private data
const int rows; // should be 'unsigned int'
const int columns;
vector<vector<int> > board;
};
其他解决方案:
假设你知道 rows
和 cols
在编译时你可以使用 template
.这和初始化一样好 row
和 col
在构造函数中。
template<unsigned int row, unsigned int col>
class OthelloState {
public:
...
private:
int board[row][col];
};
用法:
OthelloState<8,8> obj;
OthelloState<10,10> obj;
关于C++使用构造函数中的值初始化类中的二维基本数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7975256/