如何通过双指针将二维数组作为只读函数传递给函数
How to pass 2D array as read only to function by double pointer?
我需要传递指向2D数组的第一个元素的双指针,以防止函数修改2D数组中的任何元素。我想我可以用const引用-int** const &board
来完成它,但它并没有像我预期的那样工作。此外,2D数组不能声明为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
不会使数据只读。请参阅第二个链接中的错误:
- http://www.ideone.com/mnKc9(演示
int** const
( - http://www.ideone.com/BOvUL(演示
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
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);
}
没有强制转换或复制必要的
相关文章:
- "error: no matching function for call to"构造函数错误
- 什么时候调用组成单元对象的析构函数
- 继承函数的重载解析
- 为什么随机数生成器不在void函数中随机化数字,而在main函数中随机化
- C++模板来检查友元函数的存在
- 递归函数计算序列中的平方和(并输出过程)
- 对RValue对象调用的LValue ref限定成员函数
- C++17复制构造函数,在std::unordereded_map上进行深度复制
- 将数组作为参数传递给函数安全吗?作为第三方职能部门,可以探索他们想要的之外的其他元素
- 在C++STL中是否有Polyval(Matlab函数)等价物?
- 为什么使用 "this" 指针调用派生成员函数?
- 非常量调用 const 成员函数失败,只读位置C++
- 如何将 std::unique_ptr<Parent> 与具有受保护虚拟析构函数的只读父类一起使用
- 函数上的关键字'const'意味着对象字段完全只读?
- 在函数中传递只读向量时,冗长真的值得吗?const vector<const string>&
- 在另一个函数/构造函数 [C++] 中初始化后使变量只读
- 如何在不复制的情况下将只读向量传递给作为<int> pair<int,int>向量一部分的函数
- 只读变量是不能赋值的c++模板函数
- 如何在聚合根类中编写只读访问器函数
- 如何通过双指针将二维数组作为只读函数传递给函数