[英]C++ pointer to 2D array
Hi I know there are a lot of similar questions but I've been through them and I can't seem to make my function work. 嗨,我知道有很多类似的问题,但我已经通过它们,我似乎无法使我的功能工作。 I need to return a pointer to a 2D array.
我需要返回一个指向2D数组的指针。 So far I am using this code:
到目前为止,我正在使用此代码:
(This code is a function in Level.cpp) (此代码是Level.cpp中的函数)
TileType* CLevel::getTiles()
{
TileType (*matrix_ptr)[31] = tiles;
return *matrix_ptr;
}
(TileType is an enum) This function is just returning one row and I obviously need both. (TileType是一个枚举)这个函数只返回一行,我显然需要两个。 Any suggestions?
有什么建议么?
Header file Level.h: 头文件Level.h:
class CLevel
{
private:
list<CBox> boxes;
TileType tiles[GRID_HEIGHT][GRID_WIDTH];
CPlayer player;
public:
CLevel();
~CLevel();
CPlayer* getPlayer();
list<CBox>* getBoxes();
TileType** getTiles();
};
Don't define getTiles(). 不要定义getTiles()。
You are completely breaking the encapsulation of the class. 你完全破坏了类的封装。 This doesn't always matter but in this case the C/C++ 2D array is not a fit structure for passing outside where its dimensions might not be known.
这并不总是重要,但在这种情况下,C / C ++ 2D阵列不适合传递到其外部可能无法知道的尺寸。
So define your operations on tiles as methods of CLevel. 因此,在tile上定义您的操作作为CLevel的方法。
What you should do is either this: 你应该做的是:
// Class declaration
class CLevel
{
public:
TileType (*getTiles())[GRID_WIDTH];
TileType tiles[GRID_HEIGHT][GRID_WIDTH];
//...
};
// Implementation
TileType (*CLevel::getTiles())[GRID_WIDTH]
{
return tiles;
}
or this: 或这个:
// Class declaration
class CLevel
{
public:
TileType (&getTiles())[GRID_WIDTH][GRID_HEIGHT];
TileType tiles[GRID_HEIGHT][GRID_WIDTH];
//...
};
// Implementation
TileType (&CLevel::getTiles())[GRID_WIDTH][GRID_HEIGHT]
{
return tiles;
}
It's a bit of a complicated declaration but read it inside out: in both cases getTiles()
is a function that returns a reference to a 2D array of tiles (the example shows two forms of syntax). 这是一个复杂的声明,但从内到外阅读:在两种情况下,
getTiles()
都是一个函数,它返回对二维拼贴数组的引用(该示例显示了两种语法形式)。 By calling getTiles()
you're actually referring to tiles
. 通过调用
getTiles()
您实际上是指tiles
。 You can even call the function it in this way: getTiles()[i][j]
. 你甚至可以用这种方式调用它:
getTiles()[i][j]
。
If you want to return a pointer to a 2d array, then your function declaration should be: 如果要返回指向2d数组的指针,那么函数声明应为:
TileType** CLevel::getTiles()
And your return should be matrix_ptr, not its pointer content (which is a one-dimension array). 你的返回应该是matrix_ptr,而不是它的指针内容(这是一维数组)。
return matrix_ptr;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.