C++ 多态性和类型转换

Mic*_* IV 0 c++ oop polymorphism

我对 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

  }
Run Code Online (Sandbox Code Playgroud)

但问题是,虽然所有这些材质都派生自 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
Run Code Online (Sandbox Code Playgroud)

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

((AnimatedMaterial)sphere.material).interpolateColor(timerSinceStart);
Run Code Online (Sandbox Code Playgroud)

c-s*_*ile 5

在C++中,你可以使用dynamic_cast来做到这一点,我相信这与C#功能最接近:

AnimatedMaterial* panim = dynamic_cast<AnimatedMaterial*>(sphere.material);
if(panim) 
  panim->interpolateColor(timerSinceStart);
Run Code Online (Sandbox Code Playgroud)