调用虚拟方法导致总线错误

Calling virtual method resulting in bus error?

本文关键字:总线 错误 虚拟 方法 调用      更新时间:2023-10-16
class Shape {
    bool intersectP(Ray &ray) {
        return false;
    }
};
class Sphere : public Shape {
    bool intersectP(Ray &ray) {
        return true;
    }
};
class GeometricPrimitive {
    Shape* shape;
    bool intersectP(Ray &ray) {
        return shape->intersectP(ray);
    }
}
bool run() {
    Shape sphere = Sphere(0, 0, -2, 1);
    GeometricPrimitive primitive1 = GeometricPrimitive();
    primitive1.shape = &sphere;
    // generate ray 
    // ...
    return primitive1.intersectP(ray)
}

我的问题是run()返回false而不是true。此外,如果我将class ShapeintersectP的定义更改为virtual bool intersectP(Ray &ray),则会出现总线错误。有什么想法吗?

代码

GeometricPrimitive* primitive1;
primitive1->shape = &sphere;

是 UB(未定义的行为)。原因是primitive1是一个尚未分配对象的指针,但它被取消引用以设置成员。

如果您不明白为什么需要分配对象,那么最好先清除该问题,然后再继续使用虚拟方法。