gpt4 book ai didi

父类(super class)中子类的C++调用方法?

转载 作者:行者123 更新时间:2023-11-30 05:23:53 30 4
gpt4 key购买 nike

我有一个父类(super class) Bullet 的 EnemyBullet 子类。现在,我使用 EnemyBullet 对象调用 Bullet 方法 Process()。我想要的是判断当前对象是否是 EnemyBullet 以区别于 Bullet Action 。我的代码是这样的,

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);
}
}
}

最佳答案

下面是一个从父类(super class)中的方法调用子类实例的方法的例子:

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 逻辑。

关于父类(super class)中子类的C++调用方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38963505/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com