2016-12-14 78 views
0

首先的私人二维数组,我是相当新的OOP所以请多多包涵......如何创建使用私有变量长度在C++中

我目前正在试图建立一个抽动-Tac Toe终端游戏在C++中,为此,我试图使用私人int _size创建一个名为char _board[_size][_size]的2d数组,但我发现一个错误,我不太明白。我在构造函数上为_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 

所以,我怎样才能解决这个错误,或者你怎么了建议我解决这个问题?

+3

通过使用'的std :: VECTOR',而不是解决问题。 –

+0

_“我确实为构造函数上的_size设置了一个值。”_在这种情况下太晚了。 –

回答

-2

你需要动态分配动态大小的内存,但不要忘了删除它在析构函数,并考虑超载你的赋值操作符和拷贝构造函数(见rule of three):

#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; 
}; 
+0

确实,但请妥善管理你的记忆... – Quentin

+0

@Quentin谢谢,这是工作正在进行中 –

+0

手动记忆管理真的没有我会推荐,其他作为学习指针的练习。之后应该避免,除非多态性需要。另外,你的代码不会被编译。 –

1

如果你不知道董事会将在编译时有多大,你应该使用动态容器来连接保留董事会数据。 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 
    } 
} 
相关问题