【问题标题】:Overriden virtual functions [duplicate]覆盖虚函数[重复]
【发布时间】:2014-02-14 14:58:22
【问题描述】:

我已经阅读了很多关于虚拟功能的内容,但我仍然无法让某些东西按我想要的方式工作。

基本上,我有以下课程:

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 模式。

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

谢谢

【问题讨论】:

标签: c++ virtual overriding irrlicht


【解决方案1】:

是否有可能让虚函数像我想的那样工作?

没有。当您从构造函数中调用一个时,它是根据正在初始化的类(在本例中为Body)而不是最终覆盖器(因为尚未初始化,因此无法安全访问)进行调度。

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

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

【讨论】:

    【解决方案2】:
    class Craft : public Body
    {
        protected:
            void setModel();
        public:
            Craft( core::vector3df Position, core::vector3df Rotation );
    };
    

    不要在 Class Craft 中使用关键字 virtual

    【讨论】:

    • virtual 有效。如果支持,override 会更好。无论如何它与OP问题无关。
    【解决方案3】:

    就像 mathematician1975 指出的那样,您应该永远不要在构造函数或析构函数中使用虚方法。

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-10-04
      • 2021-09-30
      • 2015-06-17
      • 2015-12-15
      • 2011-11-23
      • 2013-09-21
      • 1970-01-01
      相关资源
      最近更新 更多