2016-07-21 55 views
-1

這是標題:無效使用非靜態數據成員的「公告板:: N」

class Board { 
public: 
    friend class Game; 

    Board() = default; 
    Board(int n) : N(n) { } 

    Board& SetType(int, int, char); 
    void GetType(int, int); 
    Board& CreateEmptyBoard(); 
    void BoardDisplay(); 

private: 
    int N = 0;// dimension 
    char Maze[15][15]; 

    const static int MaxSize = 15; 
}; 

class Game { 
public: 
    Game() = default; 
    Game(int x, int y) : PosX(x), PosY(y) { } 

    void BuildGame(); 
    void GameDisplay(); 
    void MoveUp(); 
    void MoveDown(); 
    void MoveLeft(); 
    void MoveRight(); 

private: 
    int PosX = 0; 
    int PosY = 0; 
}; 

void Game::BuildGame() { 
    srand(time(NULL)); 
    for (int i = 0; i < Board::N; i++) { 
     for (int j = 0; j < Board::N; j++) { 
      if (i == rand() % (Board::N) && j == rand() % (Board::N)) 
       Board::Board& SetType(i, j, 'W'); 
     } 
    } 
} 

在遊戲類的成員函數void BuildGame,我想打電話給成員函數Board& SetType(int,int,char)類Board.I定義此函數在頭文件中,而不是在這裏顯示。然後我建立這個項目,我得到了invalid use of non-static data member 'Board::N''SetType' was not declared in this scopeLike this

我哪裏錯了?我找不到它。

+0

@ildjarn我嚴重懷疑這會解決問題。 –

回答

1

編譯器讓你知道你正在使用一個實例變量作爲靜態變量。一個靜態變量與整個類而不是單個對象相關聯,所以它通過類名而不是類的對象來調用。但它需要被標記爲靜態的,像這樣

class Board 
{ 
    public: 
     static Board& setType(int, int, char); 
     ... 
    private: 
     static int N; 
     ... 
} 

我本能但是告訴我,你想在一個實例級別使用它,所以你會使用寫void Game::buildGame()方法Board它創建(可能使它Game類的屬性:

void Game::BuildGame() { 
    //make your board here. alternatively make an instance of the game 
    Board myBoard(); 
    srand(time(NULL)); 
    //in the following, use myBoard as the instance of a board. 
    for (int i = 0; i < myBoard.N; i++) { 
     for (int j = 0; j < myBoard.N; j++) { 
      if (i == rand() % (myBoard.N) && j == rand() % (Board::N)) 
       myBoard.setType(i, j, 'W'); 
     } 
    } 
} 

而一個Board類,看起來像這樣你可能會想你的setType的方法來修改實例並返回,而不是返回另外主板參考無效

class Board 
{ 
    public: 
     //this one will change this particular Board instance. 
     void setType(int, int, char); 
     //this one may make sense to be static if it is a factory method 
     //but why not use a constructor instead? 
     static Board& createEmptyBoard(); 
     //maybe you meant something to reset the board to empty state. 
     void resetBoardToEmpty(); 
     ... 
    private: 
     int N; 
     ... 
} 

,而你在這,你可能會使其成爲一個struct(其成員由默認的公共),因爲它似乎是遊戲中的「隱藏」的持有人行列,這將緩解需要使用friend class(這些要謹慎使用,因爲它們可能會非常快速地變得雜亂)。使用struct也可以讓你創建一個ChessGame類來重用Board結構。

0

N不是類Board的靜態成員,因此您需要一個板的實例來訪問它。


Game類實際上需要有一個Board成員變量來實現,上述實例。

+0

謝謝。你們兩個幫我解決了這個問題。 –

相關問題