【发布时间】:2019-06-14 06:52:06
【问题描述】:
我正在尝试为 SFML 创建一个 Screen 类,但是由于某种原因,该应用程序在使用 Xcode 示例时可以正常工作,但是一旦我将窗口放入它自己的类中,它就无法正常工作。为什么会这样,我该如何解决?
这是我的代码(改编自示例):
编辑:
看完cmets,我改成下面的代码了。这仍然不显示屏幕,程序仍然退出。
#include <SFML/Audio.hpp>
#include <SFML/Graphics.hpp>
#include "ResourcePath.hpp"
class Screen{
public:
sf::RenderWindow window;
Screen(){
sf::RenderWindow window(sf::VideoMode(800, 600), "SFML window");
}
};
int main(int, char const**)
{
Screen* screen = new Screen();
// Set the Icon
sf::Image icon;
if (!icon.loadFromFile(resourcePath() + "icon.png")) {
return EXIT_FAILURE;
}
screen->window.setIcon(icon.getSize().x, icon.getSize().y, icon.getPixelsPtr());
// Load a sprite to display
sf::Texture texture;
if (!texture.loadFromFile(resourcePath() + "cute_image.jpg")) {
return EXIT_FAILURE;
}
sf::Sprite sprite(texture);
// Create a graphical text to display
sf::Font font;
if (!font.loadFromFile(resourcePath() + "sansation.ttf")) {
return EXIT_FAILURE;
}
sf::Text text("Hello SFML", font, 50);
text.setFillColor(sf::Color::Black);
// Load a music to play
sf::Music music;
if (!music.openFromFile(resourcePath() + "nice_music.ogg")) {
return EXIT_FAILURE;
}
// Play the music
music.play();
// Start the game loop
while (screen->window.isOpen())
{
// Process events
sf::Event event;
while (screen->window.pollEvent(event))
{
// Close window: exit
if (event.type == sf::Event::Closed) {
screen->window.close();
}
// Escape pressed: exit
if (event.type == sf::Event::KeyPressed && event.key.code == sf::Keyboard::Escape) {
screen->window.close();
}
}
// Clear screen
screen->window.clear();
// Draw the sprite
screen->window.draw(sprite);
// Draw the string
screen->window.draw(text);
// Update the window
screen->window.display();
}
return EXIT_SUCCESS;
}
【问题讨论】:
-
sf::RenderWindow window(sf::VideoMode(800, 600), "SFML window"); _window = &window;是你的错误。构造函数完成后,window不再存在。 -
在您的构造函数中,您将类指针分配给 local 变量。构造函数完成后,这个对象就消失了。
-
@drescherjm 那我该如何解决这个问题?
-
Screen() : window(sf::VideoMode(800, 600), "SFML window") {}