问题
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