C++ 如何从getter函数中的类返回结构数组
我有一个相对简单的问题,但我似乎找不到针对我的情况的具体答案,我只是可能没有以正确的方式处理这个问题。我有一个类似这样的类:C++ 如何从getter函数中的类返回结构数组,c++,arrays,struct,allegro,C++,Arrays,Struct,Allegro,我有一个相对简单的问题,但我似乎找不到针对我的情况的具体答案,我只是可能没有以正确的方式处理这个问题。我有一个类似这样的类: struct tileProperties { int x; int y; }; class LoadMap { private: ALLEGRO_BITMAP *mapToLoad[10][10]; tileProperties *individualMapTile[100]; public
struct tileProperties
{
int x;
int y;
};
class LoadMap
{
private:
ALLEGRO_BITMAP *mapToLoad[10][10];
tileProperties *individualMapTile[100];
public:
//Get the struct of tile properties
tileProperties *getMapTiles();
};
对于getter函数,我有一个如下的实现:
tileProperties *LoadMap::getMapTiles()
{
return individualMapTile[0];
}
我在LoadMap类中有代码,它将为数组中的每个结构分配100个平铺属性。我希望能够访问main.cpp文件中的这个结构数组,但我似乎找不到正确的语法或方法。我的main.cpp看起来像这样
struct TestStruct
{
int x;
int y;
};
int main()
{
LoadMap _loadMap;
TestStruct *_testStruct[100];
//This assignment will not work, is there
//a better way?
_testStruct = _loadMap.getMapTiles();
return 0;
}
我意识到有很多方法可以做到这一点,但我正在尽可能地保持这个实现的私密性。如果有人能为我指出正确的方向,我将不胜感激。谢谢大家!
TestStruct *_testStruct;
_testStruct = _loadMap.getMapTiles();
这将获得指向返回数组中第一个元素的指针。然后,您可以遍历其他99个
我强烈建议使用向量或其他容器,并编写不返回指向裸数组指针的getter。首先,这里,我们为什么需要TestStruct,您可以使用“tileProperties”结构本身 还有小鬼的事, tileProperties*individualMapTile[100];是指向结构的指针数组 因此,individualMapTile将在其中包含指针。 您已返回第一个指针,因此只能访问第一个结构。其他的呢
tileProperties** LoadMap::getMapTiles()
{
return individualMapTile;
}
int main()
{
LoadMap _loadMap;
tileProperties **_tileProperties;
_tileProperties = _loadMap.getMapTiles();
for (int i=0; i<100;i++)
{
printf("\n%d", (**_tileProperties).x);
_tileProperties;
}
return 0;
}
tileProperties**LoadMap::getMapTiles()
{
返回个性化地图;
}
int main()
{
LoadMap\u LoadMap;
tileProperties**tileProperties;
_tileProperties=_loadMap.getMapTiles();
对于(int i=0;i)在可能的情况下使用向量而不是数组。也直接考虑TestStult的数组/向量,而不是指针。我不能从代码示例中看出这是否适合您。
class LoadMap
{
public:
typedef vector<tileProperties *> MapTileContainer;
LoadMap()
: individualMapTile(100) // size 100
{
// populate vector..
}
//Get the struct of tile properties
const MapTileContainer& getMapTiles() const
{
return individualMapTile;
}
MapTileContainer& getMapTiles()
{
return individualMapTile;
}
private:
MapTileContainer individualMapTile;
};
int main()
{
LoadMap _loadMap;
LoadMap::MapTileContainer& _testStruct = _loadMap.getMapTiles();
}
类加载映射
{
公众:
typedef向量映射容器;
LoadMap()
:individualMapTile(100)//尺寸100
{
//填充向量。。
}
//获取平铺属性的结构
常量MapTileContainer&getMapTiles()常量
{
返回个性化地图;
}
MapTileContainer&getMapTiles()
{
返回个性化地图;
}
私人:
MapTileContainer individualMapTile;
};
int main()
{
LoadMap\u LoadMap;
LoadMap::MapTileContainer&_testStruct=_LoadMap.getMapTiles();
}