Object's structure overriding defined methods?

旧巷老猫 提交于 2019-12-24 14:49:18

问题


I have a class called Object:

class Object {
  public:
    Vector pos;
    float emittance;
    Vector diffuse;

    virtual float intersection(Ray&) {};
    virtual Vector getNormal(Vector&) {};
};

And another class which inherits it:

class Sphere: public Object {
  public:
    float radius;

    virtual float intersection(Ray &ray) {
      Vector distance;
      float b, c, d;

      distance = ray.origin - pos;
      b = distance.dot(ray.direction);
      c = distance.dot(distance) - radius*radius;
      d = b*b - c;

      cout << -b - sqrt(d);

      if (d > 0.0) {
        return -b - sqrt(d);
      } else {
        return false;
      }
    }

    virtual Vector getNormal(Vector position) {
      return (position - pos).norm();
    }
};

When I compiled the program, I was expecting it to start spitting out tons and tons of lines of text. But for some reason, that whole method (the intersection() method) is never actually called at all!

Why is my intersection() function from the Sphere class not overriding the default on found in the Object class?


回答1:


You did not declare the function as virtual and make sure that the method signature matches. Change it to:

class Object{    
    virtual float intersection(Ray) {};
    virtual Vector getNormal(Vector) {};
}

class Sphere: public Object {
    ...
    virtual float intersection(Ray ray) {
...



回答2:


Firstly, the derived class takes a reference, and the Object class does not. Secondly, the Object declares them as non-const, and the Sphere defines them as const. These both mean that you're not actually overriding the same function.



来源:https://stackoverflow.com/questions/6271665/objects-structure-overriding-defined-methods

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!