c++多态性和类型转换

C++ polymorphism and type casting

本文关键字:类型转换 多态性 c++      更新时间:2023-10-16

我对c++比较陌生,我一直在使用OpenGL开发一个基本的3D渲染引擎。我有以下问题:我有一个叫做GeomEntity的类,它是所有几何原语的基类。我还有一个叫做DefaultMaterial的类,它是所有材质的基类(由不同类型的着色器程序组成)。因为我要有许多类型的材质,比如:ColorMaterial,TextureMaterial,AnimatedMaterial等等。我需要在GeomEntity类中添加一个对材质的引用,这样我就可以在主应用程序中使用这个函数设置任何材质:

  void GeomEntity ::addMaterial (const DefaultMaterial *mat){
         material=mat;////material is the member variable pointer of type DefaultMaterial
  }

但事情是,虽然所有这些材料都是从DefaultMaterial派生的,他们都有自己独特的方法,我不能触发,如果我引用他们DefaultMaterial的变量默认情况下。例如在主应用程序中:

  Sphere sphere;
  ....
  sphere.addMaterial(&animMaterial);///of type AnimatedMaterial
  sphere.material->interpolateColor(timerSinceStart);
   ///doesn't happen anything  as the sphere.material is
  /// of type DefaultMaterial that has   no interpolateColor() method

我知道我可以使用模板或强制类型转换但我想听听c++中这种多态性的最佳实践。在Java或c#中,我真的会使用这样的东西:

((AnimatedMaterial)sphere.material).interpolateColor(timerSinceStart);

在c++中,你可以使用dynamic_cast来做到这一点,我相信这是最接近c#特性的:

AnimatedMaterial* panim = dynamic_cast<AnimatedMaterial*>(sphere.material);
if(panim) 
  panim->interpolateColor(timerSinceStart);

如果您确定sphere.material指向一个与interpolateColor方法相关联的对象,您可以使用static_cast(如果有疑问,那么您将使用dynamic_cast)。假设AnimatedMaterial类有interpolateColor方法:

static_cast<AnimatedMaterial*>(sphere.material)->interpolateColor(timerSinceStart);

你可以强制转换,它看起来像:

static_cast<AnimatedMaterial*>(sphere.material)->interpolateColor(...);

但是用盲汉的方法,它更干净。


原答案因问题编辑而无效:

<罢工>你说:

//material is the member variable pointer of type DefaultMaterial

看看你使用它的方式,它实际上不是一个指针。如果是的话,一切都可以正常工作了。

void GeomEntity::addMaterial( DefaultMaterial *mat )
{
    material = mat; // material is the member variable pointer of type DefaultMaterial*
}

传递多态对象时,应该使用指针,而不是引用。

为什么不直接使用:

Sphere sphere;
//....
sphere.addMaterial(*animMaterial);  //of type AnimatedMaterial
animMaterial->interpolateColor(timerSinceStart);

既然animMaterial已经是正确的类型?