虚函数实现中的问题

4

我在实现母类的虚函数时遇到了一些问题: 基本上,我的代码如下:

   class Shape
    {
        public:

        virtual ~Shape();
        virtual bool Intersect (const Ray& ray, double& t) const =0;// to premit abstraktion (definition in sub-classes)
        virtual Vector GetNormal(const Vector& at) const =0;

        protected:
        Color  color;
        double dc; //diffusive component

    };

class Ball: public Shape
{
public:

    Ball(const Color& col,const double diff,const double x,const double y,const double z,const double radius):
   cx(x),cy(y),cz(z),r(radius)
    {
        Shape::color=col;
        Shape::dc=diff;
        assert(radius!=0);
    }
    virtual bool Intersect (const Ray& ray, double& t)
    {
        Vector c(cx,cy,cz), s(ray.xs,ray.ys,ray.zs);
        Vector v(s-c);

        double delta(std::pow(v*ray.dir,2)-v*v+r*r);
        if(delta<0) return false;

        const double thigh(-v*ray.dir+std::sqrt(delta)), tlow(-v*ray.dir-std::sqrt(delta));

        if(thigh<0) return false;
        else if (tlow<0){t=thigh; return true;}
        else{t=tlow; return true;}

        assert(false);//we should never get to this point
    };
    virtual Vector GetNormal(const Vector& at)
    {
        Vector normal(at - Vector(cx,cy,cz));
        assert(Norm(normal)==r);// the point where we want to get the normal is o the Ball
        return normal;
    };
private:
    // already have color and dc
    double cx,cy,cz; //center coordinates
    double r;//radius
};

在主函数中,使用以下语句创建一个Ball对象:ball=new Ball(parameters);

出现了错误提示:"cannot allocate an object of type ball because implemented funktionsare pure within ball"。

由于Ball类中的一些函数是纯虚函数,在子类中需要进行实现,因此我不理解为什么无法创建对象。


你为什么要使用 new,Jack? - Shoe
1个回答

16

您没有覆盖 IntersectGetNormal。您需要在 Ball 中将它们设置为 const

virtual bool Intersect (const Ray& ray, double& t) const { ... }
virtual Vector GetNormal(const Vector& at) const { ... }

在C++11中,您可以使用override修饰符来让编译器告诉您关于错误的信息:
virtual Vector GetNormal(const Vector& at) override // ERROR!

完美无缺。运行良好,甚至还有警告 :) - user2351468

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接