C ++通过访问器函数返回私有2D数组

时间:2018-11-21 10:14:09

标签: c++ arrays multidimensional-array

我有一个C ++类,该类具有一个函数,该函数从同一类的另一个变量获取2D数组,以便该数组的特定实例可以访问另一个变量。有问题的变量是2D数组。给定下面的代码,您将如何实现访问器函数以获取私有2D数组变量。我的意图是让访问器返回2d数组,但是我无法弄清楚要使用哪种返回类型。 int [] [],int **,int *和int不起作用。

class MyClass{
  public:
    // gets private x variable from another MyClass variable
    void proccessVar(const MyClass& aVar){
      // get and process the 2D array by calling getX()
      // int temp[10][10];
      // temp = aVar.getX();
      // proccess temp 2D array
    }

    // Return 2D array x
    int** getX(){
      return x;
    }

  private:
    int x[10][10] = {{0},{0}}; // initialized value
}

2 个答案:

答案 0 :(得分:3)

int x[10][10]

x是10个整数的10的二维数组。

让我们衰减到一个指针:

int (*y)[10] = x;

y是指向10个整数的数组的指针。

您应返回一个指向10个整数的数组的指针:

int (*getX())[10] {
  return x;
}

或者重新考虑使用并使用std :: array。

答案 1 :(得分:1)

现有答案(将指针返回一维数组)有效,但以下内容可能会减少混乱。

想法是返回对二维数组的引用。语法为:

class MyClass
{
    ...
    int (&getX())[10][10]
    {
        return x;
    }
};

或者,使用typedef

using myarray = int[10][10];
class MyClass
{
    ...
    myarray& getX()
    {
        return x;
    }
};

所有这些解决方法是因为C ++无法从函数/方法返回数组。