c++ - 添加 Sprite 时窗口关闭

标签 c++ sprite sfml

当我尝试使用我创建的函数时,我的窗口崩溃了, 我用它在屏幕上创建 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/

相关文章:

c++ - 使用鼠标单击和鼠标拖动(Opengl)绕立方体

c++ - 查看数字是否包含在未排序的两个数字区间内的最有效方法?

jquery - 在更改背景图像位置时避免看到 'scroll effect' 的技术

c++ - 为什么我的纹理会旋转 90 度?

c++ - 为什么我们在大括号前需要分号?

c++ - 奇怪的指针行为

c++ - Spritebatch 只绘制第一个 Sprite

android - Unity3d android 2d Sprite 放置

c++ - 为 clion (windows) 配置 SFML

c++ - 如何从凸形中形成凹形?