当我尝试使用我创建的函数时,我的窗口崩溃了, 我用它在屏幕上创建 Sprite ,但由于某种原因它崩溃了。
我得到错误:
Segmentation fault (core dumped)
这是我的代码:
#include <SFML/Graphics.hpp>
#include <SFML/System.hpp>
#include <string>
#include <unistd.h>
#include <iostream>
#include <vector>
using namespace std;
vector<sf::Sprite*> Tiles;
void createTile (string TextureIN, int x, int y) {
sf::Vector2f Pos(x, y);
sf::Texture Texture;
Texture.loadFromFile(TextureIN);
sf::Sprite *Tile;
Tile->setTexture(Texture);
Tile->setPosition(Pos);
Tiles.push_back(Tile);
}
int main()
{
sf::RenderWindow window(sf::VideoMode(800, 600), "My window");
createTile("Recources/grass.png", 50, 50);
while (window.isOpen())
{
sf::Event event;
while (window.pollEvent(event))
{
if (event.type == sf::Event::Closed)
window.close();
}
window.clear(sf::Color::Blue);
for (int i; i < Tiles.size(); i++) {
window.draw(*Tiles[i]);
}
window.display();
}
return 0;
}
我之前有一个可以工作的版本,但是我的电脑死机了,我忘记了 备份 >.<
无论如何,我希望你能帮我解决这个问题。
最佳答案
您正在创建一个没有适当内存分配的指针。
所以代替
sf::Sprite *Tile;
使用
sf::Sprite *Tile = new sf::Sprite;
一定要看看How to avoid memory leaks when using a vector of pointers to dynamically allocated objects in C++?
关于c++ - 添加 Sprite 时窗口关闭,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43790312/