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

Returning and using a pointer to a multidimensional array of another class

本文关键字:数组 指针 另一个 返回      更新时间:2023-10-16

我正试图通过房间类本身的函数访问"房间"数组,即:

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

我在指针方面做了一些错误的事情,但我真的不确定,什么可以纠正代码,这样我就可以访问船类之外的房间阵列?注意:假设房间已经启动

我在指针方面做了一些错误的事情,但我真的不确定

您错误地假设2D数组可以衰减为指向指针的指针,就像1D数组可以衰减到指针一样。

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];
}

我不会坚持使用std::vector等,尽管你的老师应该从一开始就教你使用它们。所以让我们坚持用C++编写C。不能将2D数组作为双指针返回,因为前者不会衰减到后者。如果你坚持返回一个指向数组的指针,你需要的是

room* (*getrooms())[4] // define a function returning a pointer to array-4 of room*
{
    return rooms;
}

这是因为例如CCD_ 2类型的2D阵列衰减为指向CCD_ 3的阵列-B的指针。

我认为问题的根本原因是让rooms了解shipship了解rooms的循环依赖性。

我建议采用不同的设计:

class Ship
{
  Room ship_rooms[3][4];  // Note, not dynamically allocated.
  public:
    void move_unit(Room& from_room, Room& destination)
    {
      destination.set_unit(from_room.get_unit());
    }
    void move_unit(unsigned int from_row, unsigned int from_column,
                   unsigned int dest_row, unsigned int dest_column)
    {
      ship_rooms[dest_row][dest_column].set_unit(ship_rooms[from_row][from_column].get_unit());
    }
    Room& get_room(unsigned int row, unsigned int column)
    { return ship_rooms[row][column]; }
};

在上述设计中,Ship负责在房间之间移动单元。房间将获得(剪切)单元或设置单元(接收)。这样就不需要一个房间来了解"飞船"的任何信息。

另一种可能的设计是让一个房间把东西移到另一个房间:

class Room
{
  Item unit;
  public:
    void receive_unit(const Room& other)
    {
      unit = other.unit;
    }
    void transfer_unit(Room& other)
    {
      other.unit = unit;
    }
};

上述结构允许房间在不了解船舶或集装箱的情况下相互通信。

注意:这些设计通过不需要指针来解决指针的问题。取而代之的是引用。

落选者:请在评论中添加解释