c++ - SFML 中的段错误

标签 c++ sfml

我正在尝试使用 SFML 制作一个非常简单的程序,但我一直遇到段错误。 我现在只是想制作一个窗口,当我将所有内容都放在主要功能中时它可以正常工作,但是当我尝试制作一个类时它会一直出现段错误。

这是我的代码:

main.cpp

int main()
{
    Graphics g(1000, 500, "Window");
    return (0);
}

Graphics.h

class Graphics
{
public:
    Graphics(int width, int height, std::string name);
    ~Graphics();

private:
    sf::RenderWindow _window;
    int _width;
    int _height;
};

Graphics.cpp

Graphics::Graphics(int width, int height, std::string name)
{
//  this->_window = new sf::RenderWindow(sf::VideoMode(width, height), name);
    this->_window.setTitle(name);
    this->_window.setSize(sf::Vector2u(width, height));
    this->_width = width;
    this->_height = height;
}

Graphics::~Graphics()
{
}

它在构造函数的第一行出错:

this->_window.setTitle(name);

我还尝试将 _window 设为指针并使用新的 sf::RenderWindow 对其进行初始化,但它以相同的方式出现段错误。

我以前在 Linux 上经常使用 SFML,但从未遇到过这个问题。这是我第一次在 Windows 上使用它。

最佳答案

sf::Window 的默认构造函数不初始化窗口。您需要使用方法 create() 手动执行此操作,例如: this->_window.create(sf::VideoMode(width, height), name) 或者,我更推荐使用的是使用成员初始化列表在构造函数中初始化窗口:

Graphics::Graphics(int width, int height, std::string name)
    :    window(sf::RenderWindow(sf::VideoMode(width, height), name))
{
...
}

关于 SFML-s 文档的更广泛解释 here .

关于c++ - SFML 中的段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47998104/

相关文章:

c++ - 如何更改 unordered_map 中的键?

c++ - 最后在C++的链表中添加节点

c++ - SFML 试图将类的引用作为参数传递给函数

c++ - SFML vsync 始终开启?

c++ - 找不到图像

c++ - C++ 服务器上的线程同步

c++ - JsonCpp 在退出函数时抛出 LogicError

c++ - 在 Linux 上链接期间出现 "Nonrepresentable section on output"错误

c++ - Pthread 行为 C++

c++ - For 循环中的 Switch 语句无法检查特定值的变量