2013-12-19 54 views
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 
}; 

,並在主球*球=新球(參數);

我收到以下消息「無法分配類型球的對象,因爲實現的funktions在球內是純的」。

我不明白爲什麼這是行不通的,因爲在子類中實現...

+0

,傑克? – Shoe

回答

16

你是不是覆蓋IntersectGetNormal。你需要讓他們constBall

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

在C++ 11,可以使用override specifier使編譯器告訴你關於你的錯誤:你爲什麼要使用`new`

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

簡單完美。工作正常,我甚至有警告:) – user2351468