2016-12-14 35 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 
    } 
} 
相關問題