c++ - sf::Sprite 是白色矩形(纹理试图通过引用传递)

标签 c++ pointers reference pass-by-reference sfml

这是resources.h:

extern sf::Sprite Sprite00;

void load_sprite(sf::Sprite &externalSprite, sf::Texture &externalTexture) ;
void draw_sprite(sf::RenderWindow &window, sf::Sprite &externalSprite);
void setposition_sprite(sf::Sprite &externalSprite, float x, float y);

这是resources.cpp:

sf::Sprite Sprite00;


void load_sprite(sf::Sprite &externalSprite, sf::Texture &externalTexture)
{
    externalSprite.setTexture(externalTexture);
}
void draw_sprite(sf::RenderWindow &window, sf::Sprite &externalSprite)
{
    window.draw(externalSprite);
}
void setposition_sprite(sf::Sprite &externalSprite, float x, float y)
{
    externalSprite.setPosition(x, y);
}

void loadResources()
{
    sf::Texture myTexture;
    myTexture.loadFromFile("images/block3d.png");

    load_sprite(Sprite00, myTexture);
}

game.cpp中:

void Game::render()
{
    window.clear(); 

    setposition_sprite(Sprite00, 100, 100);
    draw_sprite(window, Sprite00);

    window.display();
}

显示的 Sprite 是白色矩形,纹理丢失。我不知道如何解决它。我猜我没有正确传递引用。

loadResources 在 main.cpp 中被调用。例如,我想在函数 Game::render(); 的 game.cpp 中显示此 Sprite00。另外,如果我想在另一个 cpp 的其他地方显示它,我应该怎么做才能使它正确?

最佳答案

sf::Sprite 存储指向您提供的纹理的指针。但是在您的 loadResources 函数中,您正在创建一个本地 sf::Texture 对象,并将其应用于您的 Sprite 。当函数返回时,纹理被销毁,你的 Sprite 留下一个悬垂的指针。您需要确保纹理的生命周期至少包括您使用 Sprite 的持续时间。

请注意 the documentation 中对 sf::Sprite 类的描述有一段警告你正在做什么:

It is important to note that the sf::Sprite instance doesn't copy the texture that it uses, it only keeps a reference to it. Thus, a sf::Texture must not be destroyed while it is used by a sf::Sprite (i.e. never write a function that uses a local sf::Texture instance for creating a sprite).

关于c++ - sf::Sprite 是白色矩形(纹理试图通过引用传递),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46269357/

相关文章:

c++ - 仅专门化嵌套模板

c# - Visual Studio 2010 "System.Web"引用未解决 [C#]

c - 在c中查找指向制表符的两个指针之间的间隔

c++ - 在 C++ 中返回当前对象 (*this)?

c++ - 从函数返回对数据的引用会导致悬空引用问题

c++ - 在构造函数的初始化列表中将 c-style-string 转换为 std::string

c++ - 为范围内的所有数字返回相同值的哈希?

c++ - 未解析的外部符号

c - 如何更好地从指向某个地址的地址读取值

c++ - 释放指针 vector ,但内存仍在使用中