不显示使用 class 创建的 Sprite

Not displaying Sprite created with class

我在 Pickup.h 中为我的拾音器创建了一个 class。 这将是:

class Pickup
{
private:
    Sprite m_Sprite;
    int m_Value;
    int m_Type;
public:
Pickup (int type)
{
    m_Type = type;
    if (m_Type == 1)
    {
        Sprite m_Sprite;
        Texture health;
        health.loadFromFile("health.png");
        m_Sprite.setTexture(health);
    }
    else ...

}
void spawn()
{
    srand((int)time(0) / m_Type);
    int x = (rand() % 1366);
    srand((int)time(0) * m_Type);
    int y = (rand() % 768);
    m_Sprite.setPosition(x, y);
}
Sprite getSprite()
{
    return m_Sprite;
}
};

如果我尝试在屏幕上绘制一个使用 class 创建的 Sprite,使用

Pickup healthPickup(1);
healthPickup.spawn();

在进入游戏循环之前,在游戏循环中放置

    mainScreen.draw(healthPickup.getSprite());

我从来没有在屏幕上看到那个雪碧。我尝试使用

制作另一个 Sprite
Sprite m_Sprite2;
Texture health2;
health2.loadFromFile("health.png");
m_Sprite2.setTexture(health2);
m_Sprite2.setPosition(healthPickup.getSprite().getPosition().x, healthPickup.getSprite().getPosition().y);

如果我尝试在游戏循环中显示它,一切正常。我的问题是:为什么这不适用于我创建的 class?

来自构造函数:

Pickup (int type)
{
    m_Type = type;
    if (m_Type == 1)
    {
        Sprite m_Sprite;
        ...

这里定义了一个局部变量,与成员变量同名。这将创建一个局部变量,该变量将超出范围并被破坏。

构造函数未初始化成员变量。


正确解决您的问题,您需要做两处更改:首先是构造成员变量m_Sprite。二是不定义局部变量

像这样:

Pickup (int type)
    : m_Sprite()    // Constructor initializer list, default-constructs the m_Sprite member
{
    m_Type = type;
    if (m_Type == 1)
    {
        // Don't define a local variable m_Sprite
        Texture health;
        health.loadFromFile("health.png");
        m_Sprite.setTexture(health);
    }
    ...
}

您的代码应该是:

class Pickup
{
private:
    Sprite m_Sprite;
    int m_Value;
    int m_Type;
public:
Pickup (int type)
{
    m_Type = type;
    if (m_Type == 1)
    {
        Texture health; // removed the declaration of m_Sprite that was here.
        health.loadFromFile("health.png");
        m_Sprite.setTexture(health);
    }
    else ...

}
void spawn()
{
    srand((int)time(0) / m_Type);
    int x = (rand() % 1366);
    srand((int)time(0) * m_Type);
    int y = (rand() % 768);
    m_Sprite.setPosition(x, y);
}
Sprite getSprite()
{
    return m_Sprite;
}
};