2011-04-23 41 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