重载一个函数,以便它可以将基数 class 转换为派生的 class 作为参数

Overload a function so that it can convert a base class to a derived class as a parameter

我正在尝试为 3D 世界建模,其中包含球体和胶囊体对象。我以形状 class 为基础 class 并且球体和胶囊 classes 继承自基础 class 的方式对其进行建模(如果我实现它正确地,是一个完全虚拟的 class)。

class Shape
{

protected:
    COLORREF color;

public:
    virtual COLORREF getColor() =0;


};


    class Capsule: public Shape
{

private:
    Point start;
    Direction direction;
    int dist, r;
    //Color color;
    //COLORREF color;

public:

    Capsule(Point start, Direction direction, int inputdist, int inputr, COLORREF inputcolor);

    COLORREF getColor();

};

    class Sphere : public Shape
{

private:
    int r;
    Point p;
    //Color color;
    //COLORREF color;

public:
    Sphere(int x, int y, int z , int r, COLORREF inputcolor) ;
    COLORREF getColor();
    Point getpoint();
    int getradius();
};

然后我在另一个 class 中有一个函数,它接受一个指向 Sphere 对象的指针或一个指向 Capsule 对象的指针。

bool Collideswith(Sphere *s);
bool Collideswith(Capsule *c);

但我想在调用时强制调用上述函数之一

Shape *myshape = new Sphere(0,0,0,4, RGB(0,0,0));
 if(myRay.Collideswith(myshape)) { blah... }

但问题是,由于 Collideswith 只接受指向胶囊的指针或指向球体的指针,所以当我现在调用它时,它不会接受指向我传入的内容的指针,这是指向一个形状。

我无法改变我正在传递形状指针的事实,但我需要弄清楚如何让 Collideswith() 函数采用形状指针。 (也许通过创建一个重载函数来获取形状指针,并能以某种方式确定该形状是胶囊还是球体?)

如有任何建议,我们将不胜感激。 谢谢

在您的 Shape class 中声明一个虚方法:

class Shape {

// ...

    virtual bool CollidesWith()=0;
};

并在你的每个子classes中实现它:

bool Sphere::CollidesWith()
{
   // ...
}

bool Capsule::CollidesWith()
{
   // ...
}

现在,让其中的每一个调用您在问题中提到的另一个 class 中的其他 CollidesWith() 方法之一,只需传递 this.

如果您愿意,可以实现另一个重载:

bool CollidesWith(Shape *s)
{
      return s->CollidesWith();
}

您的虚拟方法可以采用您需要的任何其他参数,并在必要时转发它们。例如,您的虚拟方法可以在您的示例中采用 myRay 参数,并且每个子 class 只需调用 myRay,就像您所需代码的示例一样。