【问题标题】:How to return an array of structs from a class in a getter function如何从getter函数中的类返回结构数组
【发布时间】:2013-02-21 05:28:35
【问题描述】:

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

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

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

【问题讨论】:

标签: c++ arrays struct allegro


【解决方案1】:
TestStruct *_testStruct;
_testStruct = _loadMap.getMapTiles();

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

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

【讨论】:

    【解决方案2】:

    首先,这里,为什么我们需要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;
    }
    

    【讨论】:

      【解决方案3】:

      尽可能使用向量而不是数组。还可以直接考虑 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();
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2020-05-31
        • 1970-01-01
        • 2020-03-03
        • 1970-01-01
        • 2019-05-06
        • 1970-01-01
        • 2013-10-12
        • 2023-03-26
        相关资源
        最近更新 更多