如何使用私有变量作为C 的长度创建私人2D阵列

How to create a private 2d-array using private variables as length in c++

本文关键字:创建 2D 阵列 何使用 变量      更新时间:2023-10-16

首先,我对OOP很新,所以请忍受我...

我目前正在尝试在C 中创建一个TIC-TAC脚趾终端游戏,为此,我正在尝试使用私有int _size创建一个名为char _board[_size][_size]的2D阵列,但我发现了一个错误,我不喜欢非常了解。我确实在构造函数上对 _size的值进行了ASIGN。

非静态数据成员板的使用无效:: _ size'

board.h:

#ifndef BOARD_H
#define BOARD_H

class Board
{
    public:
        Board(int size);
        void printBoard();
    private:
        int _size;
        char _board[_size][_size];
};
#endif // BOARD_H

那么,我该如何解决此错误,或者您如何建议我解决此问题?

如果您不知道编译时板的大小,则应使用动态容器来包含板数据。99%的时间将是std::vector

class Board
{
    public:
        Board(size_t size); // better to use size_t than int for container sizes
        void print(); 
        size_t width() { return _board.size(); }
    private:
        std::vector<std::vector<char>> _board;
};
// This is not completely intuitive: to set up the board, we fill it with *s* rows (vectors) each made of *s* hyphens
Board::Board(size_t size) : 
                        _board(size, std::vector<char>(size, '-'))
                        {}

您可以(应该!)使用基于范围的循环显示输出。这将适用于向量或内置阵列。定义类模板类的函数在类主体之外使用此语法:

void Board::print() { // Board::printBoard is a bit redundant, don't you think? ;)
  for (const auto &row : _board) {    // for every row on the board,
    for (const auto &square : row) {  // for every square in the row,
      std::cout << square << " ";     // print that square and a space
    }
    std::cout << std::endl;           // at the end of each row, print a newline
  }
}

您需要动态分配动态大小的内存,但不要忘记将其删除在destructor中,并考虑将任务运算符和复制构造函数重载(请参阅三个规则):

#ifndef BOARD_H
#define BOARD_H

class Board
{
    public:
        Board(int size){
           _size = size;
           _board = new char*[size];
           for(int i =0; i < size; i++) 
              _board[i] = new char[size];
        }
        ~Board(){
           for(int i =0; i < _size; i++) 
              delete[] _board[i];
           delete[] _board;
        }
        Board(const Board &other){
          //deep or shallow copy?
        }
        operator=(const Board& other){
          //copy or move?
        }
        void printBoard();
    private:
        int _size;
        char **_board;
};
#endif // BOARD_H

但是,如果您不必使用原始内存,请考虑使用向量向量的向量,该向量将为您照顾内存管理:

class Board
{
    public:
        Board(int size);
        void printBoard();
    private:
        int _size;
        std::vector<std::vector<char> > _board;
};