C++(Arduino包装器)问题:我正在连接LCD的Arduino上编写射击游戏-

我有一个基类(Sprite),从这个其他类派生-AlienMissilePlayer。 Alien类的构造函数还具有私有(private)成员pMissile(指向Missile类的指针)-“我认为,在对象内的对象”将是描述此问题的一种方式。
[当Alien发射导弹时,导弹将其(x,y)坐标传递给导弹,并且导弹具有从Alien的坐标开始移动的自己的方法]

我的问题是:如何通过Alien对象访问导弹的坐标?
下面是简化的代码,我还绘制了类的表示形式:

// Bass class - has a form/shape, x and y position
class Sprite
{
  public:
    Sprite(unsigned char * const spacePtrIn, unsigned int xInit, unsigned int yInit);
    virtual void Move() = 0;
    void Render() { display.drawBitmap(x,y, spacePtr, 5, 6, BLACK); }
    unsigned int getX()    const { return x; }
    unsigned int getY()    const { return y; }
  protected:
    unsigned char *spacePtr;
    unsigned int x, y;
};


// Derived class "Missile", also a sprite and has a specific form/shape, and specific (x,y) derived from input sprite
class Missile : public Sprite
{
public:
   Missile(): Sprite(&spaceMissile[0], 0, 0) {}
   virtual void Move();  // its own method of moving
};

// Derived class "Alien" - has a specific form/shape, and specific (x,y) position
class Alien : public Sprite
{
public:
   Alien();
   virtual void Move();   // its own method of moving
private:
   Missile *pMissile;
};

Alien::Alien(): Sprite(&spaceAlien[0], random(5, 75), random(4, 10))
{
  Missile MissileArray[MaxAmmoSize];
  pMissile = &MissileArray[0];
}


void Alien::Move()
{
  if( random(10) % 2 == 0 )
    x += 1;
  if( random(10) % 3 == 0 )
    y += 1;

  if( (pMissile != NULL) && (random(10) == 1) )
  {
    pMissile->setCoord(x, y);
    pMissile->Move();  // move the missile
    pMissile++;        // move onto the next missile in the array
  }
  Render();
}

/*****************************************************************************************/
Alien MONSTER;
Player HERO;
Alien *pMONSTER = &MONSTER;

void loop()
{
  display.clearDisplay();
  MONSTER.Move();
  HERO.Move();
  pMONSTER->getX(); // this is x location of MONSTER
  **// how does pMONSTER access pMissile(x,y) within MONSTER.**
  delay(100);
  display.display();
}

Embedded C++ Class interaction

最佳答案

常见的方法是向Alien添加getter函数:

class Alien {
public:
    Missile* getMissile() { return pMissile; }
}

要使用它:
Alien* a = getAlienFromSomewhere();
auto pMissile = a.GetMissile();
if (pMissile != NULL) {
    x = pMissile->getX();
    y = pMissile->getY();
}

09-07 07:48