2014-02-14 129 views
1

我已经阅读了很多关于虚拟功能的内容,但是我仍然无法获得某些功能来满足我的需求。Overriden虚拟功能

基本上,我有下面的类:

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

我创建新类继承车身,这种想法是,我重写“则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)); 
} 

然而,它始终会创建一个立方体的模型,而不是我的蝰蛇模式,当我创建工艺的新实例。

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

感谢

+1

你应该避免在构造函数中调用虚函数http://stackoverflow.com/questions/962132/calling-virtual-functions-inside-constructors – mathematician1975

+0

你如何创建对象?请向我们展示使用情况,这是这种情况下非常重要的部分。 –

回答

3

是否有可能得到虚函数的工作就像我在想什么?

号当你调用一个从构造函数,它根据正在初始化类(Body在这种情况下),而不是最终的置换器(因为尚未初始化布控,所以不能安全访问)。

还是我需要改变我的构造函数以在各自的类中创建模型?

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

0

像mathematician1975指出,你应该从来没有在构造函数或析构函数内使用虚拟方法。

通过构造函数构建的对象不能被视为构造函数的类直到控制流离开构造函数。每当你在Craft的构造函数中调用一个虚拟方法时,你总是会调用一个Body的方法。由于设置模型意味着从文件中加载网格,这通常是一项相当昂贵的操作,所以我建议您在真正需要它之前不要这样做,也就是说,无论何时请求模型。在这一点上,你的虚拟应该像你期望的那样行事。

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

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

+1

'虚拟'是有效的。如果支持,“覆盖”会更好。无论如何,这与OP问题无关。 – Jarod42