我需要傳遞指向二維數組的第一個元素的雙指針,以阻止該函數修改二維數組中的任何元素。我想我可以用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