2011-04-23 63 views
0

我需要傳遞指向二維數組的第一個元素的雙指針,以阻止該函數修改二維數組中的任何元素。我想我可以用const參考 - int** const &board來做到這一點,但它不能像我預期的那樣工作。此外,二維數組不能聲明爲const,因爲它應該可以在該函數之外修改。這種功能如何可能?在這裏工作,簡化代碼中,我使用它:如何將二維數組作爲只讀函數通過雙指針傳遞?

#include <iostream> 

class player 
{ 
public: 
    player(){} 
           // returns player move 
    int move(int** const &board) 
    { 
     board[1][1] = 9; // should be illegal 
     return 9; 
    } 
}; 

class game 
{ 
    int** board;  
    player *white, *black; 

public: 
    game(player* player1, player* player2): white(player1), black(player2) 
    { 
     int i, j; 

     board = new int* [8]; 

     for(i = 0; i < 8; i++) 
     { 
      board[i] = new int [8]; 
      for(j = 0; j < 8; j++) 
       board[i][j] = 0; 
     } 
    } 
       // gets moves from players and executes them 
    void play() 
    { 
     int move = white->move(board); 

     board[2][2] = move; // should be legal 
    } 
       // prints board to stdout 
    void print() 
    { 
     int i, j; 

     for(i = 0; i < 8; i++) 
     { 
      for(j = 0; j < 8; j++) 
       std::cout << board[i][j] << " "; 
      std::cout << std::endl; 
     } 
    } 

}; 

int main() 
{ 
    game g(new player(), new player()); 

    g.play(); 
    g.print(); 
} 
+0

相反周圍傳遞數組的,我建議你封裝在'board'類中排列並通過引用傳遞。你知道,OO,封裝和所有的東西。 – fredoverflow 2011-04-23 17:40:47

回答

5

我看到你的代碼,最有趣的部分是這樣的:

int move(int** const &board) 
{ 
    board[1][1] = 9; // should be illegal 
    return 9; 
} 

如果你想board[1][1] = 9是非法的,那麼你就已經聲明參數爲:

int move(int const** &board); 
//int move(int** const &board); doesn't do what you want 

是有區別的:int** const不會使只讀數據。見第二個鏈接錯誤:

,如果你寫的參數,因爲它會更好:

int move(int const* const * const &board); 

因爲這會使一切都變成const:以下所有的分配都是非法的:

board[1][1] = 9; //illegal 
board[0] = 0;  //illegal 
board = 0;  //illegal 

在這裏看到的錯誤:http://www.ideone.com/mVsSL

現在一些圖:

int const* const * const 
    ^ ^ ^
    |  |  | 
    |  |  | 
    |  |  this makes board = 0 illegal 
    |  this makes board[0] = 0 illegal 
    this makes board[1][1] = 9 illegal 
+1

感謝您的完整答覆。我之前嘗試過(int const **),但它不會編譯,因爲我將非const參數傳遞給函數。令人驚訝的是我(int const * const * const)編譯沒有任何錯誤。我有點困惑。 – lojtas 2011-04-23 16:20:51

+0

@lojtas:即使'int const **'也會編譯。你在其他地方做錯了。 – Nawaz 2011-04-23 16:21:58

+0

@lojtas:順便說一句,你今天加入了,歡迎來到Stackoverflow。我還應該告訴你,通過點擊刻度標記,接受最令人滿意地回答你的問題的帖子。 – Nawaz 2011-04-23 16:25:32

0
void f(const int* const* arr) 
{ 
    int y = arr[0][1]; 
    // arr[0][1] = 10; // compile error 
    // arr[0] = 0; // compile error 
} 

void g() 
{ 
    int** arr; 
    arr[0][1] = 10; // compiles 
    f(arr); 
} 

沒有必要強制轉換或複製

+0

謝謝!它工作,更簡單。太糟糕了,我不能給2接受蜱:/。 – lojtas 2011-04-23 16:45:26