2013-10-13 16 views
0

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

我有一個從類 - 基本繼承三類

(I)類雪碧 - (貝司類)有一個位圖的形狀和在LCD上(X,Y)位置

(ⅱ)類導彈:公共的Sprite - 具有特定的形狀,(X,Y),並且還需要一個物鏡

(ⅲ)類外來:公共的Sprite - 具有特定的形狀和(X,Y)

(IV)類球員:公共雪碧 - 「」

他們都有着動人的不同(虛擬)方法,並顯示在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(); 
+0

你問如何在已傳遞給另一個函數一個函數訪問的變量。這是不可能的:你確定這是你想要的嗎? – suszterpatt

回答

2

由於MissileSprite一個子類,好像他們是導彈的成員,您可以訪問Sprite::xSprite::y。這是通過簡單地寫x(或如果你堅持要求this->x)。

launchpoint您在構造函數中引用的引用現在已消失,因此您的Missile::Move memfunction無法再訪問它。

如果在此期間成員xy改變,但你想要的值,你可以保存到launchpoint的引用(這可能是危險的,它被摧毀),或者你必須保持副本原始座標。

+0

由於位掩碼,以確保我明白 - 我想訪問(通過)精靈的X,而不是導彈的X:浮動溫度=雪碧:: X; //浮子=這個 - > X –

+0

@JakeFrench:由於只有一個'x'在'Move'成員函數的範圍內,所有的這些做同樣的事情:'x','這個 - > x', 'Sprite :: x','this-> Sprite :: x'。目前您處於「移動」範圍內,您無法再訪問「launchpoint」對象。如果你需要這些信息,那麼當你仍然在構造函數*中時,你必須單獨存儲它。 – bitmask