2011-02-09 92 views
1

我有这样的代码: std :: vector不保留数据?


void BaseOBJ::update(BaseOBJ* surround[3][3]) 
{ 
    forces[0]->Apply(); //in place of for loop 
    cout << forces[0]->GetStrength() << endl; //forces is an std::vector of Force* 
}

void BaseOBJ::AddForce(float str, int newdir, int lifet, float lifelength) {

Force newforce; 
newforce.Init(draw, str, newdir, lifet, lifelength); 
forces.insert(forces.end(), &newforce); 
cout << forces[0]->GetStrength(); 

}

现在,当我打电话AddForce并无限力之一的实力,COUT的1.但是,当更新被调用,它只是输出0 ,仿佛这支部队已不在那里。

回答

4

您正在存储一个指向强制的指针,但强制是局部函数。您必须使用new在堆上创建。

Force* f = new Force; 
forces.push_back(f); 
+0

谢谢,工作就像一个魅力! +1 – Chris 2011-02-09 21:14:55

3

您需要与新创建力:

Force *newforce = new Force; 
newforce->Init(draw, str, newdir, lifet, lifelength); 
forces.insert(forces.end(), newforce); // or: forces.push_back(force); 

与您的代码会发生什么事是你的对象保持在栈上,你离开的功能和做其他事以后,它被覆盖。

为什么指向矢量?可能你想要一个Force的矢量,而不是Force *。在将它扔掉之前,你还必须删除你的矢量的所有元素!