调用虚拟方法导致总线错误
Calling virtual method resulting in bus error?
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 Shape
中intersectP
的定义更改为virtual bool intersectP(Ray &ray)
,则会出现总线错误。有什么想法吗?
代码
GeometricPrimitive* primitive1;
primitive1->shape = &sphere;
是 UB(未定义的行为)。原因是primitive1
是一个尚未分配对象的指针,但它被取消引用以设置成员。
如果您不明白为什么需要分配对象,那么最好先清除该问题,然后再继续使用虚拟方法。
相关文章:
- 总线错误,堆上分配的内存
- 总线错误 10 - 字符 * 数组
- C/C++ 字符串错误与 ARM SEG 故障总线错误
- 获取总线错误:10 并附加字符串
- 多维矢量总线错误
- 链表的总线错误(核心转储)
- C 结构中的总线错误
- 如何解决此总线错误
- 调用虚拟方法导致总线错误
- 尝试打印数组时出现总线错误和奇怪的输出
- 尝试在共享内存中写入时发生总线错误
- C++ 总线错误:尝试解析和更新字符串时出现 10
- 我在以下代码中收到总线错误
- 总线错误:10 还有更多索引要去
- 使用链表的动态队列//总线错误:10(C++)
- 快速修复程序给出的总线错误
- 总线错误10或分段错误11
- C++ 在类成员"无符号长"上使用"^="和"<<"时出现总线错误
- 析构函数中的模拟总线错误
- 试图获取vector迭代器的值时出现总线错误10