嵌入式C ++类交互

时间:2013-10-13 18:56:49

标签: c++ class inheritance interaction

我正在继续使用嵌入式微控制器(Arduino)的游戏,我对课堂互动有疑问 - 这个问题从我之前的问题here继续,我的代码基于我的建议sheddenizen(请参阅“此处”中给定链接的回复):

我有三个继承自基类的类 -

(i) class Sprite - (bass class)在LCD上有位图形状和(x,y)位置

(ii) class Missile:public Sprite - 具有特定的形状,(x,y)并且还带有一个obj

(iii) class Alien:public Sprite - 具有特定的形状和(x,y)

(iv) class Player:public Sprite - “”

它们都有不同的(虚拟)移动方法,并显示在LCD上:

enter image description here

我的简化代码如下 - 具体来说,我只希望导弹在某些条件下发射:当创建导弹时它需要一个物体(x,y)值,如何在一个物体内访问一个传递的物体值继承了类?

// Bass class - has a form/shape, x and y position 
// also has a method of moving, though its not defined what this is  
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 X() const { return x; } 
    unsigned int Y() const { return y; }
  protected:
    unsigned char *spacePtr;
    unsigned int x, y;
};

// Sprite constructor
Sprite::Sprite(unsigned char * const spacePtrIn, unsigned int xInit, unsigned int yInit)
{
  x = xInit;
  y = yInit;
  spacePtr = spacePtrIn;
}

/*****************************************************************************************/
// Derived class "Missile", also a sprite and has a specific form/shape, and specific (x,y) derived from input sprite
// also has a simple way of moving
class Missile : public Sprite
{
public:
   Missile(Sprite const &launchPoint): Sprite(&spaceMissile[0], launchPoint.X(), launchPoint.Y()) {}
   virtual void Move();
};

void Missile::Move()
{
  // Here - how to access launchPoint.X() and launchPoint.Y() to check for 
  // "fire conditions" 
  y++;
  Render();
}


// create objects
Player HERO;
Alien MONSTER;
Missile FIRE(MONSTER);

// moving objects 
HERO.Move(); 
MONSTER.Move();
FIRE.Move();  

1 个答案:

答案 0 :(得分:2)

由于MissileSprite的子类,因此您可以访问Sprite::xSprite::y,就像它们是导弹的成员一样。只需简单地写x(或this->x,如果你坚持的话)。

您在构造函数中获得的launchpoint引用现已消失,因此您的Missile::Move内存函数无法再访问它。

如果在此期间成员xy已更改,但您想要原始值,则可以保存对launchpoint的引用(可能是危险的,它被破坏了)或者你必须保留原始坐标的副本。

相关问题