1

我有一个相对简单的问题,但我似乎无法找到适合我的案例的答案,而且我可能没有以正确的方式解决这个问题。我有一个看起来像这样的类:

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

我意识到有很多方法可以解决这个问题,但我试图让这个实现尽可能私密。如果有人能指出我正确的方向,我将不胜感激。谢谢!

4

3 回答 3

2
TestStruct *_testStruct;
_testStruct = _loadMap.getMapTiles();

这将为您提供指向返回数组中第一个元素的指针。然后,您可以遍历其他 99 个。

我强烈建议使用向量或其他容器,并编写不返回指向此类裸数组的指针的 getter。

于 2013-02-21T05:33:47.090 回答
0

首先,在这里,我们为什么需要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;
}
于 2013-02-21T11:35:13.430 回答
0

尽可能使用向量而不是数组。还可以直接考虑 TestStruct 的数组/向量,而不是指向它们的指针。我无法从您的代码示例中判断这是否适合您。

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();
}
于 2013-02-21T12:02:16.793 回答