如何在 C++ 中制作指针矩阵 getter

How to make a pointer matrix getter in C++

正如我在标题中所说,我如何编写必须 return 私有变量 m_board.

的函数 getBoard()

M_board 是指向其他 class 的指针的 non-dynamic 矩阵,称为 Box

class Board
{
public:

    Board() {}

    void initializeBoard();
    void putPieces(vector<vector<Pice*>>& player1, vector<vector<Pice*>>& player2);

    Box* getBoard() { return m_board; }
    
    static void convertCoordinates(char rowAct, int colAct, int& row, int& col);
private:

    Box* m_board[COL][ROW];
};

在我看来,您正在尝试构建一个二维元胞自动机。 https://en.wikipedia.org/wiki/Cellular_automaton

正如一些评论所建议的那样,使用现代 C++ 代码更容易做到这一点,这意味着 std::vector 和智能指针。

我发现这样做一次又一次。因此,创建一些基本代码来组织二维单元格是个好主意。稍后,每当您需要做这样的事情时,您都可以复制基本代码并专注于对单元格(在您的特定情况下为框)的详细行为进行编码,而不必一遍又一遍地发明 2D 网格行为。

这是一个建议的 class 二维元胞自动机界面。

#include <vector>
#include <memory>
namespace cell
{

/// Individual cell
class cCell
{
public:
    cCell();
    int ID()
    {
        return myID;
    }
    static void RestartID()
    {
        myLastID = -1;
    }
private:
    static int myLastID;
    int myID;
};
typedef std::shared_ptr< cCell > cell_t;

/// A 2D cell automaton
class cAutomaton
{
public:
    /** CTOR
        @param[in] w width
        @param[in] h height
    */
    cAutomaton(
        int w, int h );

    /** Pointer to cell
        @param[in] w zero-based width index
        @param[in] h zero-based height index
        @return shared pointer to cell

        The pointer can be used to acess methods of specialized cell class.

        Exception thrown if w or h out of bounds
    */
    cell_t cell(
        int w, int h );

    /** neighbours
        @param[in] w zero-based width index of cell
        @param[in] h zero-based height index of cell
        @return vector of shared pointers to cell's neighbours
    */
    std::vector< cell_t > neighbours(
        int w, int h );

    /** w, h co-ordinates of cell
        @param[out] w width
        @param[out] h height
        @param[in] cell
    */
    void coords(
                int& w, int& h,
                cell_t cell );

private:
    std::vector< cell_t > myCell;
    int myWidth;
    int myHeight;
};
}

您可以在 https://github.com/JamesBremner/autocell

查看一种实现方法