RenderWindow 不能跨多个函数工作

RenderWindow not working across multiple functions

我是 SFML 的新手,一直在观看将所有内容都放在一个主函数中的教程。自己做程序的时候,想把它拆分成多个函数,但是不能正常工作,谁能解释一下为什么这样:

#include <SFML/Graphics.hpp>
#include <iostream>

    int main()
    {
        sf::RenderWindow window(sf::VideoMode(512, 512), "window", sf::Style::Resize | sf::Style::Close);
        while (window.isOpen())
    {
        sf::Event evnt;
        while (window.pollEvent(evnt))
        {
            if (evnt.type == evnt.Closed)
            {
                window.close();
            }
        }
        window.clear();
        window.display();
    }
    return 0;
}

而这不是:

#include <SFML/Graphics.hpp>
#include <iostream>

sf::RenderWindow window;

void setup()
{
    sf::RenderWindow window(sf::VideoMode(512, 512), "window", sf::Style::Resize | sf::Style::Close);
}

int main()
{
    setup();
    while (window.isOpen())
    {
        sf::Event evnt;
        while (window.pollEvent(evnt))
        {
            if (evnt.type == evnt.Closed)
            {
                window.close();
            }
        }
        window.clear();
        window.display();
    }
    return 0;
}

它们都会编译和 运行,但在前者中,window 将保持打开状态,而在后者中,它不会。

您在 setup() 声明的 window 变量正在覆盖全局 window。目的。尝试以下操作:

void setup()
{
    window.create(sf::VideoMode(512, 512), "window", sf::Style::Resize | sf::Style::Close);
}