Embedded C++ Class interaction

2019-09-14 22:33发布

问题:

I'm continuing with a game for an embedded microcontroller (Arduino), and I have a question on class interaction -- this question continues from my previous question here and I have based my code on the suggestion of sheddenizen (see response to the given link in 'here'):

I have three classes that inherit from a base class-

(i) class Sprite - (bass class) has a bitmap shape and (x,y) position on an LCD

(ii) class Missile : public Sprite - has a specific shape, (x,y) and also takes a obj

(iii) class Alien : public Sprite - has specific shape and (x,y)

(iv) class Player : public Sprite - ""

They all have different (virtual) method of moving and are shown on the LCD:

My streamlined code is below - specifically, I only want the missile to fire under certain conditions: when missile is created it takes an objects (x,y) value, how can I access a passed objects value within an inherited class?

// 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:

Since Missile is a subclass of Sprite you can access Sprite::x and Sprite::y as if they were members of Missile. That is by simply writing x (or this->x if you insist).

The launchpoint reference that you got in the constructor is gone by now, so your Missile::Move memfunction cannot access it any more.

If in the meantime the members x and y changed, but you want the original value, you can either save a reference to launchpoint (which might be dangerous, it is destroyed) or you have to keep a copy of the original coordinates.