簡體   English   中英

嵌入式C ++類交互

[英]Embedded C++ Class interaction

我與嵌入式微控制器(Arduino的)比賽繼續進行,我對課堂互動的一個問題-這個問題從我剛才的問題繼續在這里 ,我已經根據我的sheddenizen的建議代碼(見對給定鏈接'here'):

我有三個繼承自基類的類 -

(i) 類Sprite - (低音類)在LCD上具有位圖形狀和(x,y)位置

(ii) 類導彈:公共精靈 - 具有特定形狀,(x,y)並且還采用對象

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

(iv) class Player:public Sprite - “”

它們都有不同的(虛擬)移動方法,並顯示在LCD上:

在此輸入圖像描述

我的簡化代碼如下 - 具體來說,我只希望導彈在某些條件下發射:當導彈創建它需要一個對象(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();  

由於MissileSprite的子類,因此您可以訪問Sprite::xSprite::y ,就好像它們是Missile的成員一樣。 那就是簡單地寫x (如果你堅持的話, this->x )。

launchpoint您在構造函數中得到參考現在走了,所以你的Missile::Move memfunction不能再訪問它。

如果在此期間成員xy發生了變化,但是你想要原始值,你可以保存對launchpoint的引用(可能是危險的,它被銷毀),或者你必須保留原始坐標的副本。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM