代码之家  ›  专栏  ›  技术社区  ›  Christopher Settles

重载函数,以便将基类转换为派生类作为参数

  •  3
  • Christopher Settles  · 技术社区  · 7 年前

    我正在尝试模拟一个3D世界,里面有球体和胶囊。我以这样一种方式对其建模:shape类是基类,sphere和capsule类继承自基类(如果我正确实现了它,它是一个完美的虚拟类)。

    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();
    };
    

    然后我在另一个类中有一个函数,它接受指向球体对象的指针或指向胶囊对象的指针。

    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... }
    

    我无法改变传递形状指针的事实,但我需要弄清楚如何让CollizeSwith()函数接受形状指针。(可能通过创建一个重载函数,该函数接受形状指针,并可以计算出形状是胶囊还是球体?)

    任何建议都将不胜感激。 谢谢

    1 回复  |  直到 7 年前
        1
  •  3
  •   Sam Varshavchik    7 年前

    Shape 类别:

    class Shape {
    
    // ...
    
        virtual bool CollidesWith()=0;
    };
    

    并在每个子类中实现它:

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

    CollidesWith() 您在问题中提到的另一个类中的方法,简单地传递 this .

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

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

    myRay 参数,每个子类只调用 麦雷 ,与所需代码的示例完全相同。