c++多态性和类型转换
C++ polymorphism and type casting
我对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
已经是正确的类型?
- 如何使用静态多态性在 int 和指针类型之间进行转换?
- 如何调用指针类型的方法(禁用多态性)?
- 使用多态性时在子对象之间进行转换?
- 如何为多态性中的指定类型分配内存
- C 多态性:允许模棱两可的成员类型
- 如何避免使用模板类型的派生类进行多态性动态强制转换
- 自动复制=按值并支持多态性的适当类型的非静态字段
- 具有不同模板类型的子类的多态性
- 多态性并获取C++中的对象类型
- C 模板和多态性无缝合用户定义的转换
- 多态性(继承)和价值类型
- c++多态性:基类的上转换/下转换和容器,缺少数据
- C++技术:类型擦除与纯多态性
- 具有 dynamic_cast 和类型标识的 C++ 多态性
- 多态性和类型转换
- 如何使用基类指针调用派生类非虚拟成员函数,而无需类型转换和使用多态性
- 数据类型和多态性
- c++多态性和类型转换
- C++ 多态性和派生类类型 - "ugly programming"指针类型转换
- 根据"foreign"子类型采取特定操作,不带开关、强制转换等。我们可以以某种方式使用多态性吗?