1

I used the Fireworks init function to store a particle into the particles vector class. And when I try to retrieve the count of the particles vector in the update() function, the particles vector is empty. Why?

Fireworks.cpp class:

void Fireworks::init(){
    float x = randf();
    float y = - 1 * randf(); //Going UP
    float z = randf();

    Particle part(position,Vector3f(x,y,z), color, randInt(1,50));
    particles.push_back(part);
}

bool Fireworks::update(){
    Particle particle;
    int count = particles.size(); //Total num of particles in system
    cout << particles.size() << " ";
}

class Fireworks: public ParticleSystem {
private:
  void init();

public:

  Fireworks(Vector3f pos, Vector3f col) {
    position = pos;
    color = col;
    init();
  }

  virtual bool update();
};

particlesystem.h

class ParticleSystem {
protected:
  vector<Particle> particles;

public:
  //virtual Particle generateParticle();
  virtual bool update(){return false;};
};

main.cpp

ParticleSystem *PS;
int main( int argc, char *argv[] ) {
  PS = &Fireworks(Vector3f(0,0,0), Vector3f(200,0,255));
  glutIdleFunc(move);
}

void move()
{
   PS->update();       
}
4

1 回答 1

3
PS = &Fireworks(Vector3f(0,0,0), Vector3f(200,0,255));

这引入了未定义的行为。右侧创建一个临时的,将在完整的表达式结束后立即删除(即在 之后;)。PS将在该行之后指向已删除的对象 - 对其进行任何操作都是未定义的行为。

使用new.

PS = new Fireworks(Vector3f(0,0,0), Vector3f(200,0,255));

此外,您必须从所有声明为返回某些东西(非 void)的函数返回。它们是否是虚拟的并不重要。

于 2012-11-10T14:21:10.747 回答