2016-08-15 2 views
1

У меня есть подкласс EnemyBullet суперкласса Bullet. Теперь я вызываю метод Bullet Process() с помощью объекта EnemyBullet. Я хочу, чтобы определить, является ли текущий объект EnemyBullet отличным от действия Bullet. Мой код, как это,Метод вызова C++ для подкласса в суперклассе?

void Bullet::Process(float deltaTime) 
{ 
// Generic position update, based upon velocity (and time). 
m_y = m_y + this->GetVerticalVelocity()*deltaTime; 
m_pSprite->SetY(static_cast<int>(m_y)); 
m_pSprite->SetX(static_cast<int>(m_x)); 

    if (m_y < 0) 
    { 
    SetDead(true); 
    } 

//Here I want to detect current object is an EnemyBullet, then define a different action 
//I tried the following code, but it didn't work 
if (EnemyBullet* v = static_cast<EnemyBullet*>(Bullet)) { 
    if (m_y >800) 
    { 
     SetDead(true); 
    } 
} 
} 
+5

Вы, по крайней мере, хотите 'dynamic_cast' вместо' static_cast'. Но почему бы не просто переопределить метод в EnemyBullet? –

+0

Возможный дубликат [Проверить для производного типа (C++)] (http://stackoverflow.com/questions/2355195/check-for-derived-type-c) –

+0

@TavianBarnes Я пробовал как 'dynamic_cast', так и' static_cast' и не работал. Переопределение было бы неплохо, но я не понимаю, почему мой код не работает. – Wilheim

ответ

1

Вот пример вызова метода экземпляра подкласса от метода суперкласса:

class Bullet { 
public: 
    void process() { 
    // update m_y... 

    // update sprite position... 

    if (this->isDead()) { 
     // handle dead bullet... 
    } 
    } 

    virtual bool isDead() { 
    return (m_y < 0); 
    } 

protected: 
    int m_y; 
}; 

class EnemyBullet : public Bullet { 
public: 
    bool isDead() override { 
    return (m_y > 800); 
    } 
}; 

Обратите внимание, как каждый тип пули имеет собственный isDead логику ,

Смежные вопросы