2013-10-13 14 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