简体   繁体   English

添加精灵时窗口关闭

[英]Window closes when adding a sprite

My window crashes when I try to use my function I created, I use it to create a sprite on screen but for some reason it crashes. 当我尝试使用自己创建的函数时,我的窗口崩溃了,我用它在屏幕上创建了一个精灵,但是由于某种原因它崩溃了。

I get the error: 我收到错误:

Segmentation fault (core dumped) 分段故障(核心已转储)

and here's my code: 这是我的代码:

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

I had a working version before but my computer crashed and I forgot to back it up >.< 我之前有一个可用的版本,但是我的计算机崩溃了,我忘记了对其进行备份>。<

Anyways, I hope you can help me with this issue. 无论如何,希望您能为我解决这个问题。

You are creating a pointer without proper memory allocation. 您创建的指针没有适当的内存分配。

So instead of 所以代替

sf::Sprite *Tile; 

use 采用

sf::Sprite *Tile = new sf::Sprite;

Be sure to have a look on How to avoid memory leaks when using a vector of pointers to dynamically allocated objects in C++? 一定要看一看如何使用指针向量在C ++中动态分配对象时如何避免内存泄漏? as well. 也一样

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM