获取用户定义的类的实例

时间:2012-01-22 09:07:08

标签: c++ class

我是C ++的初学者,现在我的一个课程出了问题。我有一个我的Sprite类的向量列表,我希望获得列表中的一个项目,并将其提供给另一个类的方法参数,但它只是告诉我Subscript range is out of vector。我查看了列表,看它是否真的包含任何项目,这是正确的,列表工作得很好。

我的清单:

vector<Core::Graphic::cSprite> Sprites;

我的方法:

Core::Logic::cGameObject::cGameObject(std::string Name, Core::Graphic::cSprite* Sprite, float X, float Y, int Depth)
{ 
    // Set fields
    this->Name = Name;
    this->Sprite = *Sprite;
    // Add to active sprites
    for(int i = 0; i < this->Sprite.Images.size(); i++)
    {
        // Create temporaroy sprite
        sf::Sprite tempSprite;
        tempSprite.SetImage(this->Sprite.Images[i]);
        this->ActiveSprite.push_back(tempSprite);
    }
    this->X = X;
    this->Y = Y;
    this->Depth = Depth;
    this->ImageIndex = 0;
    this->ImageNumber = this->Sprite.SubFrames;
}

我的精灵构造函数:

Core::Graphic::cSprite::cSprite(std::string Name, vector<std::string> ImagesFileNames)
{
    // Check input
    if(Name != "" && ImagesFileNames.max_size() > 0)
    {
        this->Name = Name;
        for(int i = 0; i < ImagesFileNames.size(); i++)
        {
            sf::Image tempImage;
            if(tempImage.LoadFromFile(ImagesFileNames[i])){
              this->Images.push_back(tempImage);
            }
        }
        this->SubFrames = this->Images.max_size();
    }
}

我有一个cGameObjectManaher类来管理游戏对象,它有一个如下方法:

Game.GameObjectManager.AddGameObject("obj_intro_1", &Game.SpriteManager.Sprites[0], 0, 0, 0);

我检查了我的代码中的所有内容,但没有超出列表。我认为这是我实施的代码问题。

感谢。

1 个答案:

答案 0 :(得分:1)

您的代码正在使用max_size(),它返回理论上可以添加到向量的系统最大值,而不是size(),它返回向量的实际大小。你展示的代码可能不是代码崩溃,而是一些代码依赖于这个 - &gt;子框架在后面的代码片段中设置为一个巨大的数字。

例如,在我的机器上;

std::vector<int> a;
std::cout << a.max_size() << std::endl;

返回4611686018427387903而不是0,这可能是你期待的。

相关问题