gpt4 book ai didi

c++ - 如何将二维数组作为只读传递给双指针函数?

转载 作者:太空宇宙 更新时间:2023-11-04 16:32:07 25 4
gpt4 key购买 nike

我需要传递指向二维数组第一个元素的双指针,以防止函数修改二维数组中的任何元素的方式起作用。我以为我可以用 const reference - 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();
}

最佳答案

我看了你的代码,有趣的部分是:

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);

因为这使得所有内容都为常量:那么以下所有赋值都是非法的:

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

关于c++ - 如何将二维数组作为只读传递给双指针函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5765141/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com