覆盖虚拟功能

时间:2014-02-14 14:58:22

标签: c++ virtual method-overriding irrlicht

我已经在虚拟功能上阅读了很多内容,但我仍然无法按照自己的意愿获得工作。

基本上,我有以下课程:

class Body
{

    protected:
        scene::ISceneNode* Model;
        virtual void setModel();
    public:
        Body( core::vector3df Position, core::vector3df Rotation );
};


Body::Body( core::vector3df Position, core::vector3df Rotation )
{
    CurrentThrust = 0;
    setModel();
    Model->setPosition( Position );
    Model->setRotation( Rotation );
}

void Body::setModel()
{
    Model = Engine::Instance->GetSceneManager()->addCubeSceneNode();
    Model->setMaterialFlag( video::EMF_LIGHTING, false );
}

我创建了继承Body的新类,我的想法是在这些类中覆盖“setModel()”,构造函数将加载我的新模型,而不是默认值;如下所示

class Craft : public Body
{
    protected:
        virtual void setModel();
    public:
        Craft( core::vector3df Position, core::vector3df Rotation );
};

Craft::Craft( core::vector3df Position, core::vector3df Rotation ) : Body(Position, Rotation)
{
    // Other stuff
}

void Craft::setModel()
{
    Model = Engine::Instance->GetSceneManager()->addAnimatedMeshSceneNode( Engine::Instance->GetSceneManager()->getMesh("resource/X-17 Viper flying.obj") );  // addCubeSceneNode();
    Model->setMaterialFlag( video::EMF_LIGHTING, false );
    Model->setScale( core::vector3df(0.1f) );
}

但是,当我创建一个新的Craft实例时,它总是创建一个Cube模型而不是我的Viper模式。

是否可以像我想的那样让虚拟功能正常工作?或者我是否需要更改构造函数以在各自的类中创建模型?

由于

3 个答案:

答案 0 :(得分:3)

  

是否有可能像我在想的那样让虚拟功能正常工作?

没有。当你从构造函数中调用一个时,根据初始化的类(在这种情况下为Body)调度它,而不是最终的覆盖(因为尚未初始化,因此无法安全访问)。

  

或者我是否需要更改构造函数以在各自的类中创建模型?

这可能是最简单的解决方案。我建议将模型作为构造函数参数传递给Body。这样,就不可能忘记设置它。

答案 1 :(得分:1)

class Craft : public Body
{
    protected:
        void setModel();
    public:
        Craft( core::vector3df Position, core::vector3df Rotation );
};

请勿在Class Craft中使用关键字virtual

答案 2 :(得分:0)

就像数学家1975所指出的那样,你应该从不在构造函数或析构函数中使用虚方法。

构造函数构建的对象不能被视为构造函数的类,直到控制流离开构造函数。每当你在Craft的构造函数中调用一个虚方法时,你总是会调用一个Body的方法。

由于设置模型意味着从文件中加载网格物体(这通常是一项非常昂贵的操作),我建议您在真正需要它之前不要这样做,即无论何时请求您的模型。此时,您的虚拟应该表现得像您期望的那样。

相关问题