我有類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