如何使用私有变量作为C 的长度创建私人2D阵列
How to create a private 2d-array using private variables as length in c++
首先,我对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;
};
相关文章:
- 读取字符串文本输入以创建 2D 矢量
- 如何使用 DXGI 格式DXGI_FORMAT_R1_UNORM创建 2D 纹理?
- 从 2 个 1D 矢量创建 2D 矢量
- 不明白使用双指针 (**) 创建 2d 动态数组
- 创建 2D 数组0xCCCCCCCC访问冲突写入位置
- 如何在C++中创建 2d 数组,其中一部分包含循环计数器,另一部分包含数字列表?
- C++ 如何创建 2D 数组,将其传递给另一个函数,然后打印
- 创建 2D 数组类:如何访问 2D 数组类(如 array[x][y))中的元素
- C++ - 创建 2D 复制构造函数
- 如何在其中创建2D字符串向量并插入数据
- 使用来自C 参数的大小创建2D数组
- C++的新增功能:创建 2D 数组并具有正确的赋值运算符:分割错误
- 如何使用矢量创建 2D 数组
- 动态创建 2D 数组时使用的大小
- 从文本文件创建 2D 字符串矢量
- 从 1D 数组创建 2D 数组
- C++以内存安全的方式使用给定向量的大小创建2D阵列
- C++ 如何动态创建 2D 矢量
- 创建2D数组时出现异常:在C++中重新抛出之前进行清理
- 基于命令行输入创建 2D 数组