加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

C双指针成员访问

发布时间:2020-12-16 07:07:07 所属栏目:百科 来源:网络整理
导读:C(Arduino包装)问题:我正在Arduino上写一个连接LCD的射击游戏 – 我有一个基类(Sprite),并从其他类派生 – 外星人,导弹和玩家. Alien类的构造函数也有私有成员pMissile(一个指向导弹类的指针) – “对象中的一个对象”将是一种描述这种情况的方法. [当外星
C(Arduino包装)问题:我正在Arduino上写一个连接LCD的射击游戏 –

我有一个基类(Sprite),并从其他类派生 – 外星人,导弹和玩家. Alien类的构造函数也有私有成员pMissile(一个指向导弹类的指针) – “对象中的一个对象”将是一种描述这种情况的方法.
[当外星人发射导弹时,它将自己的(x,y)坐标传递给导弹,导弹有自己的方法从外星人的坐标开始移动]

我的问题是:如何通过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) {}
   virtual void Move();  // its own method of moving
};

// Derived class "Alien" - has a specific form/shape,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();
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读