【问题标题】:Window closes when adding a sprite添加精灵时窗口关闭
【发布时间】:2017-05-04 18:30:25
【问题描述】:

当我尝试使用我创建的函数时,我的窗口崩溃了, 我用它在屏幕上创建一个精灵,但由于某种原因它崩溃了。

我得到错误:

分段错误(核心转储)

这是我的代码:

#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;
}

我之前有一个工作版本,但我的电脑崩溃了,我忘记了 备份它>.

无论如何,我希望你能帮助我解决这个问题。

【问题讨论】:

    标签: c++ sprite sfml


    【解决方案1】:

    您正在创建一个没有正确分配内存的指针。

    所以不是

    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++?

    【讨论】:

      猜你喜欢
      • 2023-03-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-12-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多