2013-02-21 59 views
1

我有一个相对简单的问题,但我似乎找不到适合我的案例的答案,我可能不会以正确的方式处理这个问题。我有一个类,看起来像这样:如何在一个getter函数中返回一个类的结构数组

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

我意识到有很多方法来做到这一点,但我试图尽可能保持这种实现。如果有人能指点我正确的方向,我将不胜感激。谢谢!

+0

可能重复的[从函数返回数组](http://stackoverflow.com/questions/6422993/return-an-array-from-function) – jogojapan 2013-02-21 05:33:13

回答

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

这将让你的指针数组中的第一要素返回。然后你可以遍历其他的99.

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

0

首先,在这里,我们为什么需要TestStruct,你可以使用 “tileProperties” 结构本身......

和IMP的事情, 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; 
} 
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(); 
} 
相关问题