【发布时间】:2011-06-11 16:00:42
【问题描述】:
我想使用继承来根据对象在层次结构中的位置以不同的方式处理对象
假设您构建了 Shape 对象的层次结构,例如:
class Shape {} ;
class Sphere : public Shape {} ;
class Triangle : public Shape {} ; ...
然后为 Ray 类配备如下方法:
class Ray
{
Intersection intersects( const Sphere * s ) ;
Intersection intersects( const Triangle * t ) ;
};
您存储各种类型的各种 Shape* 数组并调用
vector<Shape*> shapes ; ...
//foreach shape..
Intersection int = ray.intersects( shapes[ i ] )
但是你得到编译器错误
错误 C2664: 'Intersection Ray::intersects(const Sphere *) const' : 无法将参数 1 从 'Shape *const' 转换为 'const Sphere *'
你做错了什么?
是做到这一点的唯一方法其他方式,与
class Shape
{
virtual Intersection intersects( const Ray* ray )=0 ;
} ;
那么每个类覆盖相交?然后调用
//foreach shape..
Intersection int = shapes[i]->intersects( ray ) ;
你能按照我展示的第一种方式做吗?
【问题讨论】:
-
我认为是multiple (double) dispatch。 C++ 本身没有它。
标签: c++ inheritance