C++重载决议

bob*_*obo 7 c++ inheritance

我想使用继承来根据层次结构中的位置以不同的方式处理对象

(类似于这个C#问题)

假设您构建Shape对象的层次结构,如:

class Shape {} ;
class Sphere : public Shape {} ;
class Triangle : public Shape {} ; ...
Run Code Online (Sandbox Code Playgroud)

然后为Ray类配备如下方法:

class Ray
{
    Intersection intersects( const Sphere * s ) ;
    Intersection intersects( const Triangle * t ) ;
};
Run Code Online (Sandbox Code Playgroud)

您存储各种类型的各种Shape*的数组并调用

vector<Shape*> shapes ; ...
//foreach shape..
Intersection int = ray.intersects( shapes[ i ] )
Run Code Online (Sandbox Code Playgroud)

但是你得到了编译错误

错误C2664:'交点Ray :: intersects(const Sphere*)const':无法将参数1从'Shape*const'转换为'const Sphere*'

你做错了什么?

唯一的方法就是用另一种方式来做

class Shape
{
    virtual Intersection intersects( const Ray* ray )=0 ;
} ;
Run Code Online (Sandbox Code Playgroud)

然后每个类覆盖相交?然后打电话给

//foreach shape..
Intersection int = shapes[i]->intersects( ray ) ;
Run Code Online (Sandbox Code Playgroud)

你能以我展示的第一种方式或从未这样做过吗?

Pup*_*ppy 4

你必须反过来做。重载解析发生在编译时,当您调用它的类型是Shape*.