指向存储在第二个对象中的向量中的对象

时间:2013-09-28 22:20:25

标签: c++ function pointers vector handles

我想在处理包含指向向量中对象的指针的对象时提出一些建议。

我希望能够操纵向量的特定元素。我试图从对象中复制数据,然后我很难回头并确保更新相同的元素,所以我想简单地返回指向该元素的指针操纵该指针而不必确保更新正确的元素与数据。

我想使用动态对象的句柄。

class h_AFV{
 AFV * pAFV;   
 int * cnt;

 friend class AFV;

 public:  

 h_AFV(int);
 h_AFV(int, int, int, int);   
 h_AFV(const h_AFV& afv) : cnt(afv.cnt), pAFV(afv.pAFV){++*cnt;}
 h_AFV& operator = (const h_AFV&);
~h_AFV();...

存储在:

   std::vector<h_AFV>AFVs;

我想选择要返回的特定元素:

h_AFV* player::gtAFV(int n){       
return  new h_AFV(AFVs[n]);     <-This is how I return a pointer to the element I want to manipulate
}

然后我想将指针添加到另一个对象,其他指针或数据将修改所选元素:

void control::moveOrder(int a, int sp , bool al){

  h_AFV * ph_AFV = NULL;
  if(currentPlayer == 1){ph_AFV = pl1->gtAFV(marker);}  <-This gets the pointer
  if(currentPlayer == 2){ph_AFV = pl2->gtAFV(marker);} 

  ph_AFV->setStat(1);   <-These work I tested the pointer with some output.
  ph_AFV->setOrder('m');

  mvOrder m(ph_AFV, a, sp, al);   

  checker(ph_AFV);
  moving.push_back(m);  


  delete ph_AFV;

}

我添加了复制构造函数并重载了赋值运算符。通常,代码将一直有效,直到函数超出范围或我尝试操作存储的数据。

   void mvOrder::resolve(){
int rate = speed * .01;

        MessageBox(NULL, "Marker 1", "Marker!", MB_OK);

  int dir = pMover->gtFace() * .0174532925;   
  int DBI = pMover->gtDBI();
  int MaxSpd = data[DBI].gtRdSpeed();
  int spd = rate * MaxSpd;
        MessageBox(NULL, "Marker 2", "Marker!", MB_OK);
  int dist = spd;
  coord c = pMover->gtCoord(); 
  MessageBox(NULL, "Tank Moving", "Marker!", MB_OK);
  float tx = c.Xloc;
  float ty = c.Yloc;
  tx += (float)dist*(sin(dir));
  ty -= (float)dist*(cos(dir));
  int nx = tx;
  int ny = ty;
   pMover->setLoc(nx, ny);
   if(align){pMover->setAngle(dir);}
  else{pMover->setNAngle(dir);}

}  


 struct mvOrder{
   h_AFV * pMover;   

 int azmuth;
 int speed;
 bool align;   

 mvOrder();
 mvOrder(h_AFV*, int, int, bool);
 mvOrder(const mvOrder&);
 ~mvOrder();
  void resolve();
};

如何完成此代码并正确管理指针?

0 个答案:

没有答案