在sfml中抛出'std :: bad_alloc'实例后调用终止

时间:2020-09-13 06:07:24

标签: c++ multidimensional-array sfml

我编写了一个sfml程序,以使用sf :: RectangleShape的2D数组绘制矩形网格,并且当您按键盘上的Up键时,数组的行和列将展开。这是我的代码:

CardGrid.h

    class CardGrid : public sf::Drawable, sf::Transformable {
private:
    sf::RectangleShape** squares;
    sf::Color color;
    int rows = 1 , cols = 1;
public:
    CardGrid();
    virtual void draw(sf::RenderTarget& window, sf::RenderStates states) const;
    void addEvents();
  
    void setFillcolor(sf::Color color);
    void fillArray();
    sf::RectangleShape newRectangleShape(float x, float y);
    sf::RectangleShape** createArray();

CardGrid.cpp

CardGrid::CardGrid() {
    this->createArray();
    this->setFillcolor(sf::Color::White);
    this->fillArray();

}
void CardGrid::draw(sf::RenderTarget &window, sf::RenderStates states) const {
    for (int i = 0; i < rows; i++)
    {
        for (int j = 0; j < cols; j++)
        {
            window.draw(squares[i][j]);
        }
    }
}
void CardGrid::setFillcolor(sf::Color color) {
    this->color = color;
}
sf::RectangleShape CardGrid::newRectangleShape(float x, float y)
{
    sf::RectangleShape s;
    s.setSize({10.f,10.f});
    s.setFillColor(color);
    s.setPosition(sf::Vector2f(x+=25,y+=25));

}
void CardGrid::fillArray()
{
    float x = 10,y = 10;
    for (int i = 0; i < this->rows; i++)
    {
        for (int j = 0; j < this->cols; j++)
        {
            squares[i][j] = newRectangleShape(x,y);
        }
    }
}

sf::RectangleShape** CardGrid::createArray()
{
    squares = new sf::RectangleShape*[rows];
    for (int i = 0; i < rows; i++)
    {
        squares[i] = new sf::RectangleShape[cols];

    }
    return squares;
}
void CardGrid::addEvents() {
    if (sf::Keyboard::isKeyPressed(sf::Keyboard::Up))
    {
        this->cols += 1;
        this->rows += 1;
    }
    else if (sf::Keyboard::isKeyPressed(sf::Keyboard::Down))
    {
        this->cols -= 1;
        this->rows -= 1;
    }
}

main.cpp

#include <SFML/Graphics.hpp>
#include "CardGrid.h"
int main() {
   

     sf::RenderWindow window(sf::VideoMode(500, 500, 32), "Test");
        CardGrid grid;
        while(window.isOpen())
        {
            sf::Event event;
            while(window.pollEvent(event)){
                if (event.type == sf::Event::Closed){
                    window.close();
                }
            }
            window.clear(sf::Color::Black);
            grid.addEvents();
            window.draw(grid);
            window.display();
        }
        return 0;
    }

但是当我尝试运行程序时,遇到了此错误:

terminate called after throwing an instance of 'std::bad_alloc'
  what():  std::bad_alloc

任何人都知道问题可能在哪里以及如何解决?非常感谢您的帮助!

0 个答案:

没有答案