【问题标题】:Getter returning 2d array in C++Getter 在 C++ 中返回二维数组
【发布时间】:2012-08-24 17:16:11
【问题描述】:

这是我关于 SO 的第一篇文章,尽管我已经在这里度过了一段时间。 我在这里遇到了一个返回二维数组的函数的问题。我在我的 Game 类中定义了一个私有 2d int 数组属性 int board[6][7],但我不知道如何为这个属性创建一个公共 getter。

这些是我游戏的相关部分。h:

#ifndef GAME_H
#define GAME_H

class Game
{
public:
    static int const m_rows = 6;
    static int const m_cols = 7;

    Game();
    int **getBoard();

private:
    int m_board[m_rows][m_cols];

};

#endif // GAME_H

现在我想要的是 game.cpp 中的类似内容(因为我认为不带括号的数组名称是指向第一个元素的指针,显然它不适用于二维数组):

int **Game::getBoard()
{
    return m_board;
}

这样我就可以把它放在我的 main.cpp 中:

Game *game = new Game;
int board[Game::m_rows][Game::m_cols] = game->getBoard();

谁能帮帮我,我应该在我的 game.cpp 中放什么?

谢谢!

【问题讨论】:

    标签: c++ arrays function 2d getter


    【解决方案1】:

    您不能将数组按值传入和传出函数。但是有多种选择。

    (1) 使用std::array<type, size>

    #include <array>
    
        typedef std::array<int, m_cols> row_type;
        typedef std::array<row_type, m_rows> array_type;
        array_type& getBoard() {return m_board;}
        const array_type& getBoard() const {return m_board;}
    private:
        array_type m_board;
    

    (2) 使用正确的指针类型。

        int *getBoard() {return m_board;}
        const int *getBoard() const {return m_board;}
    private:
        int m_board[m_rows][m_cols];
    

    int[][] 不涉及指针。它不是指向整数数组的指针数组的指针,而是整数数组的数组。

    //row 1               //row2
    [[int][int][int][int]][[int][int][int][int]]
    

    这意味着一个int* 指向所有这些。要获得行偏移量,您可以执行以下操作:

    int& array_offset(int* array, int numcols, int rowoffset, int coloffset)
    {return array[numcols*rowoffset+coloffset];}
    
    int& offset2_3 = array_offset(obj.getBoard(), obj.m_cols, 2, 3);
    

    【讨论】: