我正在尝试使用 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/