C++使用构造函数中的值初始化类中的二维基本数组

标签 c++ class compilation multidimensional-array

我正在尝试编译这段代码:

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; , 如果你想初始化 rowcol在运行时。

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;  
};

其他解决方案:

假设你知道 rowscols在编译时你可以使用 template .这和初始化一样好 rowcol在构造函数中。

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/

相关文章:

c++ - 如何使用概念将参数传递给类方法?

当类成员隐藏其父类的类成员时,C++ 会生成警告吗?

c++ - C++中的结构体是按顺序分配内存的吗?不知何故每次都能得到指针比较的正确答案

Android - 在后台运行 - 服务与标准 java 类

java - 为什么Java找不到主类?

java - 在由另一个类填充的类中使用数组字段时遇到问题

c++ - 编译时检查基类是否为 "interface"

c++ - 编译 MatIO 时出现链接错误

java - 错误: identifier expected when compiling java code with package statements from command line

scala: list.flatten: 没有找到匹配参数类型 (Any) => Iterable[Any] 的隐式参数