本文介绍了Getter在C ++中返回二维数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的第一篇关于SO的文章,即使我已经花了一些时间了。
我在这里遇到了一个函数返回2d数组的问题。我在Game类中定义了一个私有的2d int数组属性 int board [6] [7] ,但是我不知道如何为该属性创建公共获取器。

this is my first post on SO, even though i've spent some time already here.I've got here a problem with a function returning a 2d array. I have defined a private 2d int array property int board[6][7] in my Game class, but i don't know how to create a public getter for this property.

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

These are relevant parts of my game.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中(因为我认为不带括号的数组名称是指向第一个元素的指针,显然它不适用于2d数组):

Now what I would like is something like this in game.cpp (cause I thought array name without brackets is a pointer to first element, obviously it doesn't work with 2d arrays) :

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

这样我就可以在main.cpp中输入这个例子:

So that i can put this for example in my main.cpp:

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

任何人都可以帮助我,我应该在游戏中放入什么内容。cpp?

Can anybody help me, what should i put in my game.cpp ?

谢谢!

推荐答案

您不能按值将数组传递到函数中或从函数中传递出去。但是有多种选择。

You cannot pass arrays by value into and out of functions. But there's various options.

(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)使用正确的指针类型。

(2) Use the correct pointer type.

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

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

An int[][] has no pointers involved. It isn't a pointer to an array of pointers to arrays of integers, it's an array of an array of integers.

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

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

Which means one int* points to all of them. To get to a row offset, you'd do something like this:

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

这篇关于Getter在C ++中返回二维数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-19 16:46