返回并使用指向另一个类的多维数组的指针
Returning and using a pointer to a multidimensional array of another class
我正试图通过房间类本身的函数访问"房间"数组,即:
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
了解ship
和ship
了解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;
}
};
上述结构允许房间在不了解船舶或集装箱的情况下相互通信。
注意:这些设计通过不需要指针来解决指针的问题。取而代之的是引用。
落选者:请在评论中添加解释
相关文章:
- 添加到数组指针
- C++语法差异:二维和一维数组(指针算术)
- 数组指针表示法C++(移动数组时)
- 复制后删除原始数组指针将前 3 个字节设置为 0
- C++访问指向结构的指针中的类数组指针
- C++编译时使用 constexpr 字符数组指针分配静态数组?
- std::flush可以用于将对象指针转换为其封闭数组指针吗
- 创建<int>对整数数组指针的矢量引用 (C++)
- 将 2D 数组指针传递给 C++ 中的函数
- 创建指针是否超过非数组指针的末尾,而不是从 C++17 中的一元运算符和未定义的行为派生?
- 队列数组指针 (C++)
- C++数组指针上的删除操作
- 对于循环不循环和检测字符数组 [指针和字符数组]
- 如何初始化数组指针对象
- 如何正确传递 2D 数组指针作为参数
- 从数组指针中获取怪异的数字
- 初始化std :: unique_ptr作为原始数组指针的初始化
- 将结构数组指针从C#传递到C
- STD :: Sort将数组指针设置为NULL
- C++数组指针错误无法将“int*”转换为“int**”