2016-05-16 102 views
4

全部。我有一個類定義如下:'this'不能用於常量表達式錯誤(C++)

class Board { 
    int columns, rows; 
    bool board[10][10]; 
public: 
    Board(int, int); 
    void nextFrame(); 
    void printFrame(); 
}; 

void nextFrame()不斷給我的錯誤,因爲[rows][columns]「‘這個’不能在一個常量表達式」對他們倆的。我怎樣才能重新定義這個,以便它工作?我明白錯誤。該函數的定義如下,並且錯誤發生在以下代碼示例的第3行。

void Board::nextFrame() { 
     int numSurrounding = 0; 
     bool tempBoard[rows][columns]; 

     for (int i = 0; i < rows; i++) 
     { 
      for (int j = 0; j < columns; j++) 
      { 
       if ((i + 1) < rows && board[i + 1][j] == true) 
       { 
        numSurrounding++; 
       } 
       if ((i - 1) >= 0 && board[i - 1][j] == true) 
       { 
        numSurrounding++; 
       } 
       if ((j + 1) < columns && board[i][j + 1] == true) 
       { 
        numSurrounding++; 
       } 
       if ((j - 1) >= 0 && board[i][j - 1] == true) 
       { 
        numSurrounding++; 
       } 
       if ((i + 1) < rows && (j + 1) < columns && board[i + 1][j + 1] == true) 
       { 
        numSurrounding++; 
       } 
       if ((i + 1) < rows && (j - 1) >= 0 && board[i + 1][j - 1] == true) 
       { 
        numSurrounding++; 
       } 
       if ((i - 1) >= 0 && (j + 1) < columns && board[i - 1][j + 1] == true) 
       { 
        numSurrounding++; 
       } 
       if ((i - 1) >= 0 && (j - 1) >= 0 && board[i - 1][j - 1] == true) 
       { 
        numSurrounding++; 
       } 

       if (numSurrounding < 2 || numSurrounding > 3) 
       { 
        tempBoard[i][j] = false; 
       } 
       else if (numSurrounding == 2) 
       { 
        tempBoard[i][j] = board[i][j]; 
       } 
       else if (numSurrounding == 3) 
       { 
        tempBoard[i][j] = true; 
       } 

       numSurrounding = 0; 

      } 
     } 
     for (int i = 0; i < rows; i++) 
     { 
      for (int j = 0; j < columns; j++) 
     { 
      board[i][j] = tempBoard[i][j]; 
     } 
    } 
} 
+1

'bool tempBoard [rows] [columns];' - 這是無效的C++語法。聲明條目數時,數組必須使用編譯時常量。 – PaulMcKenzie

+0

'bool tempBoard [rows] [columns];'是一個可變長度的數組。數組的維度必須是常量表達式。除非你的對象(class,'this')也是一個編譯時常量,否則情況就不一樣了。然而,如果'this'是'const',那麼你不能修改'board' ... – user6338625

+0

@PaulMcKenzie而不是寫「Board TempBoard」? – yeawhadavit

回答

1

您需要使用STL的集合。

下面是嵌套向量,讓您的主板爲例:您可以瞭解成員初始化語法board(vector<vector<bool>>(x, vector<bool>(y)))herehere

#include <vector> 
#include <iostream> 

using namespace std; 

class Board { 
    int columns, rows; 
    vector<vector<bool>> board; 
public: 
    Board(int x, int y) : board(vector<vector<bool>>(x, vector<bool>(y))) { 
    } 
    void nextFrame() { 
     // Fill in 
    } 
    void printFrame() { 
     // Fill in 
    } 
    size_t xdim() { 
     return board.size(); 
    } 
    size_t ydim() { 
     if (board.size() == 0) { 
      return 0; 
     } 
     return board.at(0).size(); 
    } 
}; 

int main() { 
    Board b(10, 20); 

    cout << "Made the board" << endl; 
    cout << "X: " << b.xdim() << endl; 
    cout << "Y: " << b.ydim() << endl; 
} 

相關問題