创建一个对象并将其存储在向量中会使值变得混乱

时间:2017-09-24 07:49:45

标签: c++

所以我正在尝试创建一个粒子系统,我需要创建一些粒子对象并将它们存储在一个向量中以便以后使用它们。 这样做的功能是:

$

粒子类构造函数如下所示:

void spawnLoop( std::vector<Particle*> &particleVector ){
    for (int i=0; i < 5; i++) {
        particleVector.emplace_back( new Particle(400.0, 400.0, 1.0, 1.0) );
    }
}

但是如果我在完成存储之后尝试完全遍历向量,它会给出值:1.81063e + 13。 我确实尝试过相当多的研究,但找不到任何解决方案。 编辑:

Particle::Particle(float xPos= 400,float yPos= 400,float xVel= 0,float yVel= 0) {
float xPosition = xPos;
float yPosition = yPos;
float xVelocity = xVel;
float yVelocity = yVel;
bool dead = false;
std::cout<< "We have " << xPosition  << " "<< yPosition << " "<< xVelocity << " "<< yVelocity << std::endl;
//This prints the values and they look correct
}

1 个答案:

答案 0 :(得分:2)

问题出在Particle的构造函数中。您将参数分配给局部变量,而不是实例变量。因此,稍后,当您尝试打印出这些变量的值时,它们尚未保存:

这是问题所在:

float xPosition = xPos;
float yPosition = yPos;
float xVelocity = xVel;
float yVelocity = yVel;

它应该是这样的:

_xPosition = xPos;
_yPosition = yPos;
_xVelocity = xVel;
_yVelocity = yVel;

如果所有这些变量都被定义为类的实例变量,并且getXPos()等等,则返回它们。

更好的方法是不在构造函数中分配值,而是将它们初始化为初始化列表。这是关于初始化列表的一个不错的问题/答案:C++ initialization lists for multiple variables