实现虚函数的问题

 jiushi45678 发布于 2023-02-09 10:42

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

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

并在主球*球=新球(参数);

我得到以下消息"无法分配类型球的对象,因为实现的funktions是纯粹的球内".

我不明白为什么这不起作用,因为子类中有一个实现...

1 个回答
  • 您还没有覆盖IntersectGetNormal.你需要让他们constBall:

    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!
    

    2023-02-09 10:44 回答
撰写答案
今天,你开发时遇到什么问题呢?
立即提问
热门标签
PHP1.CN | 中国最专业的PHP中文社区 | PNG素材下载 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有