我在Pickup.h中为我的皮卡创建了一个课程。 这将是:
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;
}
};
如果我尝试使用
在屏幕上绘制一个使用此类创建的SpritePickup healthPickup(1);
healthPickup.spawn();
进入游戏循环之前,并在游戏循环内放置
mainScreen.draw(healthPickup.getSprite());
我从未在屏幕上看到过Sprite。我尝试使用
创建另一个SpriteSprite m_Sprite2;
Texture health2;
health2.loadFromFile("health.png");
m_Sprite2.setTexture(health2);
m_Sprite2.setPosition(healthPickup.getSprite().getPosition().x, healthPickup.getSprite().getPosition().y);
如果我尝试在游戏循环中显示它,一切正常。我的问题是:为什么这对我创建的类不起作用?
答案 0 :(得分:2)
来自构造函数:
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);
}
...
}
答案 1 :(得分:1)
您的代码应为:
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;
}
};