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

时间:2015-03-09 06:17:08

标签: c++

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。此外,如果我将intersectPclass Shape的定义更改为virtual bool intersectP(Ray &ray),那么我会收到总线错误。有什么想法吗?

1 个答案:

答案 0 :(得分:1)

代码

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

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

如果您不理解为什么需要分配对象,那么在移动虚拟方法之前首先要解决该问题会更好。

相关问题