我需要传递指向二维数组的第一个元素的双指针,以阻止该函数修改二维数组中的任何元素。我想我可以用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();
}
相反周围传递数组的,我建议你封装在'board'类中排列并通过引用传递。你知道,OO,封装和所有的东西。 – fredoverflow 2011-04-23 17:40:47