c++ - 返回并使用指向另一个类的多维数组的指针

标签 c++ arrays class pointers

我正在尝试通过房间类本身中的函数访问“房间”数组,即:

 class ship{

    room * rooms[3][4];
 public:

   room ** getrooms(){

       return *rooms;
   }

 }


class room{

  //variables...
  ship * ship_ptr;
  public:
     getShipPtr(); //assume it returns the pointer to the class ship
     void function_x(){
    this->getShipPtr()->getrooms()->rooms[x][y]->doThat();
      }
  }

我在指针方面做错了一些事情,但我不太确定,有什么可以更正代码,以便我可以从 ship 类访问房间数组? 注:假设房间已经初始化

最佳答案

I'm doing something wrong pointer-wise but I'm not really sure

您错误地假设二维数组可以衰减为指向指针的指针,就像一维数组可以衰减为指针一样。

int arr1[10];
int* ptr1 = arr1; // OK. 1D array decays to a pointer.

int arr2[10][20];
int** ptr2 = arr2; // Not OK. 2D array does not decay to a pointer to pointer.

int (*ptr2)[20] = arr2; // OK. ptr2 is a pointer to "an array of 20" objects.

我的建议:

简化您的代码并将界面更改为:

room* getRoom(size_t i, size_t j){
   // Add checks to make sure that i and j are within bounds.
   return rooms[i][j];
}

关于c++ - 返回并使用指向另一个类的多维数组的指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34620562/

相关文章:

c++ - 是在堆上自动创建的特征矩阵吗?

php - 如何从具有嵌套键的多维中获取列

c - 声明大数组时出现堆栈溢出异常

单独 JAR 文件中的 JavaBeans 类

c++ - 在类的函数中使用 'const'

C++追加到文件的第二行

c++ - 有一个构造函数,但有两个析构函数

Java找不到类

c++ - 使用 llvm-gcc 4.x 安装 srilm 1.6.0 时出现问题

.net - 编译时数组边界