我正在尝试通过房间类本身中的函数访问“房间”数组,即:
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/