首页 > 解决方案 > 在具有其他整数成员变量的类中将 2D char 数组声明为 c++ 中的大小

问题描述

我正在使用的类如下所示。我正在解析来自 txt 文件的数据并将其保存为 numRows 和 numCols,并且我希望 2D 字符数组迷宫具有我刚刚解析的那些维度的大小。我怎样才能做到这一点?我在上大学,程序任务要求 numRows、numCols 和 2D char 数组是 Board 类的私有成员。

class Board
{
public:
    Board()
    {
        for (int i = 0; i < numRows; i++)
        {
            for (int j = 0; j < numCols; j++)
            {
                maze[i][j] = emptyPos;
            }
        }
    }
    Player getPlayer() { return User; }
    void parseMazeData(int &rowStartPos, int &colStartPos);
private:
    int numRows;
    int numCols;
    char maze[numRows][numCols];
    Player User;
};

标签: c++arraysclassmultidimensional-arraychar

解决方案


I suppose you don't know upfront the number of rows and columns, so you need to perform a dynamic allocation. If my assumption is right you need to have already parsed the maze data before doing anything with the array.

So, once you parse those dimensions you can do:

Board() {
//Parse maze data somehow before and then:
 maze = new char[nrows*ncols]
 for (int i = 0; i < numRows; i++) { 
   for (int j = 0; j < numCols; j++) { 
     maze[i][j] = emptyPos;
  }
 } 
}

This of course will require you to clean up this maze array in the destructor of this Board class.

A much nicer solution would be using std::vector, since it provides the cleanup for you. Think of it as a high level array with extra functionalities and safer API. This way, maze would be declared as:

std::vector<std::vector<char>> maze.

With that you would not need to write a destructor yourself and your constructor would be like:

Board() {
//Parse maze data somehow before and then:
 maze.size(numRows);
 for (int i = 0; i < numRows; i++) { 
    maze.at(i).size(numCols);
    for (int j = 0; j < numCols; j++) { 
       maze[i][j] = emptyPos;
    }
  } 
}


推荐阅读