C++ list looping

感情迁移 提交于 2020-03-22 09:33:07

问题


Im quite stuck here. I have been trying and googling for the past 2 days but I cant figure it out. I have a class that is called Player and another that is called Enemy that inherits from Player. I have a list that stores coordinates for my bullets and loop trough them in Player. Im trying to access and loop trough the same list to check for collision in Enemy that builds on Player, but It will not even enter the loop. I guess somehow its empty but why?

struct structShoot
{
    float x;
    float y;
};

class Player
{
private:
      blablabla
protected:
    list<structShoot>::iterator it;
    list<structShoot> shoot_list;
    structShoot test;
public:
     void render(SDL_Surface* dest);
};

void Player::render(SDL_Surface* dest)
{    
//Works fine, see the other loop down below
for(it = shoot_list.begin(); it != shoot_list.end();)
{
    shoot.moveSet(it->x, it->y);
    shoot.draw(dest);
    it->y--;

    if((it->y) < -25)
    {   
        it = shoot_list.erase(it);
    }

    else
    {
        it++;
    }   

}
}

class Enemy : protected Player
{
 public:
 void render(SDL_Surface* dest);
};

void Enemy::render(SDL_Surface* dest)
{
    SDL_Rect a, b;


    //Does not enter loop!? Ever. Why?
    for(it = shoot_list.begin(); it != shoot_list.end();)
    {
        SDL_Quit();
        a.x = enemy.getX();
        a.y = enemy.getY();
        a.w = enemy.getWidth();
        a.h = enemy.getHeight();

        b.x = it->x;
        b.y = it->y;
        b.w = 10;
        b.h = 19;
        it->y--;


        if (collision(a, b) == true)
        {
            SDL_Quit();
        }

        if(it->y < -25)
        {   
            it = shoot_list.erase(it);
        }

        else
        {
            it++;
        }   


    }
}

回答1:


You should make render virtual to use polymorphism.

virtual void render(SDL_Surface* dest);

I suppose that every time you call Player::render, because of such code:

Player* enemy = new Enemy();
enemy->render(); // there is Player::render calling

If you make render virtual you will use virtual table to detect correct function that should be called in this place. So you have to make render virtual.




回答2:


There is only one possible thing that could cause this, namely that shoot_list.begin() is equal to shoot_list.end(), thus it's empty.

Perhaps the loop at Player::render is broken and empties the list completely?



来源:https://stackoverflow.com/questions/5622658/c-list-looping

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!