我想使用继承来根据对象在层次结构中的位置以不同的方式处理对象
( similar to this C# question )
假设您构建了一个 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 ) ;
你能按照我展示的第一种方式做还是永远做不到?
最佳答案
你必须反过来做。重载决议发生在编译时,当您调用它的类型是 Shape*
时。
关于C++ 重载决议,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6316955/