线程1:EXC_BAD_ACCESS错误,此错误在第一行的CPP文件中的句柄函数中出现

THREAD 1 :EXC_BAD_ACCESS error, this error appears at the handle function in the cpp file at the first line

本文关键字:错误 一行 CPP 文件 句柄 函数 BAD EXC ACCESS 线程      更新时间:2023-10-16

这是一种创建鸡肉入侵者游戏的代码,游戏(或我可以做的任何部分(在我初始化一只鸡时工作正常,但是当我制作它时一批鸡阵列向我展示了这个错误。

RenderWindow window;
int main(int, char const**)
{
    chicken chick[4][7];
    Sprite back;
    Clock clock;
    window.create(VideoMode(1800, 1000), "Menu");
    while (window.isOpen())
    {
        Event event;
        while (window.pollEvent(event))
        {
            if (event.type == Event::KeyPressed && event.key.code == Keyboard::Escape)
                window.close();
            if (event.type == Event::Closed)
                window.close();
        }
        Texture texture;
        if (!texture.loadFromFile(resourcePath() + "background.jpg"))
        {
            std::cout << "Error loading texture" << std::endl;
        }
        Time time;
        time = clock.getElapsedTime();
        if (time.asSeconds() >= 0.001)
        {
            chick[4][7].handle(window, clock);
            clock.restart();
        }

        window.clear();
        back.setTexture(texture);
        back.setPosition(0, 0);
        back.setTextureRect(IntRect(0, 0, 1800, 1000));
        window.draw(back);
        for (int i = 0; i < 4; i++)
            for (int j = 0; j < 7; j++)
                chick[i][j].initialize(window);
        window.display();
    }
}
///////////////////
this is the app file for the chicken class
using namespace sf;
class chicken
{
private:
    RectangleShape chick;
    bool flag;
public:
    chicken();
    void initialize(RenderWindow &window);
    void handle(RenderWindow & window, Clock clock);
    ~chicken();
};
#endif /* chicken_hpp */
/////////////////////////////////////////////////////////////
this is the cpp file for the chicken class 
using namespace sf;
chicken::chicken()
{
    chick.setPosition(500, 500);
    chick.setSize(Vector2f(200, 200));
    chick.setOrigin(100, 100);
    flag = true;
}
void chicken::initialize(RenderWindow & window)
{
    Texture texture2;
    if (!texture2.loadFromFile(resourcePath() + "chicken3.jpg"))
    {
        std::cout << "Error loading texture" << std::endl;
    }
    chick.setTexture(&texture2);
    window.draw(chick);
}
void chicken::handle(RenderWindow & window, Clock clock)
{
    if (flag) //the error appears here
    {
        chick.move( 10 , 0 ) ;
    }
    else
    {
        chick.move(-10 , 0);
    }
    if (chick.getPosition().x >= window.getSize().x)
        flag = false;
    if(chick.getPosition().x < 0)
        flag = true;
}
chicken::~chicken()
{
}

将来请在问题中包含整个错误消息,但是这里的问题是您正在访问鸡肉阵列中的界限索引。

您的数组大小为4x7,这意味着您的有效索引为0-3和0-6。

您的手柄功能在小鸡[4] [7]上被调用。

如果您只想在数组中的最后一只小鸡上调用该功能,那将是

chick[3][6].handle(window, clock);

要在每只鸡上打电话给您需要双循环的双重

for(int i = 0; i < 4; ++i)
{
    for(int j = 0; j < 7; ++j)
    {
        chick[i][j].handle(window, clock);
    }
}