c++ - 实现虚函数的问题

标签 c++ class inheritance virtual-functions

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

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

我收到以下消息“无法分配类型为 ball 的对象,因为实现的函数在 ball 中是纯函数”。

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

最佳答案

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

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

在 C++11 中,您可以使用 override specifier让编译器告诉你你的错误:

virtual Vector GetNormal(const Vector& at) override // ERROR!

关于c++ - 实现虚函数的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20686314/

相关文章:

c++ - 具有常量成员的默认构造函数

java - 如何将多个对象分配给另一个类/对象?

java - 从父类返回子类

jpa - Kotlin数据类继承+拷贝方法

c++ - 如何在 Eclipse CDT 中使用 google test 管理测试输出?

c++ - 如何从 C++ 中的函数返回 vector ?

c++ - 具有不同模板类型的子类的多态性

c++ - 菱形继承(钻石问题) (C++)

c++ - MSVC 2008 16 字节结构成员对齐异常

c++ - boost::geometry 3D 多边形相交编译错误