如何通过双指针将2D数组作为只读传递给函数?

时间:2011-04-23 15:42:01

标签: c++

我需要传递双指针,它指向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();
}

2 个答案:

答案 0 :(得分: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 :(得分: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);
}

不需要演员表或复制