我有类Sphere
和Triangle
这两个都是Intersectable
的子类。 Intersectable
有一个公共成员变量colour
。请看下面的代码片段:C++为什么相同变量的值有所不同?
float t_min = 100000.0f;
pair<float, f3Vector> point_hit;
Intersectable * object_hit;
Triangle triangle;
Sphere sphere_trans;
bool hit = false;
//loop through triangles
for(unsigned int i = 0; i < mesh->tvi.size(); i++){
...
triangle = Triangle((fRGB)mesh->color[mesh->tci[i].c0], va.toVector3(), vb.toVector3(), vc.toVector3());
point_hit = triangle.intersect(orig, dir, c_near, c_far);
if(point_hit.first != 0.0f && point_hit.first < t_min){
object_hit = ▵
std::cout << "color1 " << object_hit->color << std::endl;
hit = true;
...
}
}
// loop through spheres
for(unsigned int j = 0; j < spheres.size(); j++){
...
sphere_trans = Sphere(sphere.color, center3, sphere.getRadius());
point_hit = sphere_trans.intersect(orig, dir, c_near, c_far);
if(point_hit.first != 0 && point_hit.first < t_min){
object_hit = &sphere_trans;
std::cout << "color1 " << object_hit->color << std::endl;
hit = true;
...
}
}
if(hit){
std::cout << "color2 " << object_hit->color << std::endl;
}
我期待,在如果我有各种各样的color1 (1 0 0)
和下输出的输出是color2 (...)
的值outprinted颜色应该是相同的。但是,这不会发生。事实上,我总是得到相同的输出为color2 (...)
。你能告诉我我做错了什么吗?谢谢!
这是'object_hit'分配给一个本地(for循环)在这里'object_hit =&sphere_trans;'所以使用'object_hit'在它超出范围后是未定义的行为。 –
@ShafikYaghmour我编辑了代码,以便我不再创建局部变量。但我仍然有同样的行为。 – kaufmanu