使用 SFML 和 std::thread 的编译器错误

Compiler errors using SFML with std::thread

本文关键字:编译器 错误 thread 使用 std SFML      更新时间:2023-10-16

(global(

    class lasers
    {
    public:
        Sprite sLaser;
        int ok2=0;
        void fire(Texture &t5, FloatRect bbBG, Vector2f pP)
        {
            if(ok2!=1)
            {
            sLaser.setTexture(t5);
            sLaser.setOrigin(1,-705);
            sLaser.setPosition(pP.x+20.5,pP.y+645);
            sLaser.scale(0.1f,0.1f);
            ok2=1;
            }
            while(sLaser.getGlobalBounds().intersects(bbBG))
            {
            sLaser.move(0,-2);
            sleep(milliseconds(10));
            }

        }
    };     

(主(

    Texture t5;
    t5.loadFromFile("images/laser.png");
    lasers zxcv;
    int j=0;
while (app.isOpen())
    {    
        ................
        if(Keyboard::isKeyPressed(Keyboard::Space))
            if(j==0)
            {
                thread th(&lasers::fire, &zxcv, t5, boundingBoxBORDER, sPlayer.getPosition());
                j=1;
            }
        ................
    }

(错误(

||=== Build: Debug in GAME (compiler: GNU GCC Compiler) ===|
main.cpp||In function 'int main()':|
functional||In instantiation of 'struct std::_Bind_simple<std::_Mem_fn<void (lasers::*)(sf::Texture&, sf::Rect<float>, sf::Vector2<float>)>(lasers, sf::Texture, sf::Rect<float>, sf::Vector2<float>)>':|
thread|137|required from 'std::thread::thread(_Callable&&, _Args&& ...) [with _Callable = void (lasers::*)(sf::Texture&, sf::Rect<float>, sf::Vector2<float>); _Args = {lasers&, sf::Texture&, sf::Rect<float>&, const sf::Vector2<float>&}]'|
functional|1665|**error**: no type named 'type' in 'class std::result_of<std::_Mem_fn<void (lasers::*)(sf::Texture&, sf::Rect<float>, sf::Vector2<float>)>(lasers, sf::Texture, sf::Rect<float>, sf::Vector2<float>)>'|
functional|1695|**error**: no type named 'type' in 'class std::result_of<std::_Mem_fn<void (lasers::*)(sf::Texture&, sf::Rect<float>, sf::Vector2<float>)>(lasers, sf::Texture, sf::Rect<float>, sf::Vector2<float>)>'|
||=== Build failed: 2 error(s), 4 warning(s) (0 minute(s), 1 second(s)) ===|

(问题(

不确定我做错了什么,因为这是我第一次使用线程(对于学校项目(。我已经看了几个例子,包括那些有类的例子,但不知何故,我还没有设法做到这一点。

我基本上想制作精灵,从一个点开始,向上,直到它们撞到某物并消失。所以我认为创建一个类可以在初始化和调用函数 fire 后自行处理每个对象(在我让线程工作后仍然必须向其添加一些东西(。

有人可以给我一些关于如何摆脱上面的最后两个错误并最终使线程工作的建议吗?谢谢。

lasers::fire需要Texture &

在此上下文中,编译器不知道如何从 std::thread 构造函数解析所需的lasers::fire重载,因为您是按值(没有引用(传递它的。

std::ref(t5) 包装t5,以提示编译器您正在通过引用传递它。

std::thread th(&lasers::fire, &zxcv, std::ref(t5), ..., ...);