C++ Object variables in list don't update duri

2019-09-20 14:40发布

When iterating through a list, the variables of the object in the list won't update, with debugging it looked like the variables only updated temporarily until the loop ended. Why is this? I've been looking for a very long time.

for (std::list<GUI>::iterator it = allguis.begin(); it != allguis.end(); ++it) {
    GUI gui = *it;
    speed = 5
   if (gui.activated) {
    gui.position.x = gui.position.x + gui.distanceX * speed;
    gui.position.y = gui.position.y + gui.distanceY * speed;
           }
   }                

And the GUI class:

class GUI
{
public:
    sf::Vector2f position = sf::Vector2f(0,0);
    int sizex;
    int sizey;
    bool activated;
    float rotation;
    int damage;
    float distanceX;
    float distanceY;

};

1条回答
虎瘦雄心在
2楼-- · 2019-09-20 15:14

GUI gui = *it; creates a local variable initialized with a copy of the value stored in container. You should use a refence instead:

GUI & gui = *it;

Or you can use C++11-style loop:

speed = 5; // no point in updating it on every iteration
for(auto & gui: allguis)
{
    if(gui.activated)
    {
        gui.position.x = gui.position.x + gui.distanceX * speed;
        gui.position.y = gui.position.y + gui.distanceY * speed;
    }
}  
查看更多
登录 后发表回答