2013-05-15 127 views
1

我有類SphereTriangle這兩個都是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 = &triangle; 
     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 (...)。你能告訴我我做錯了什麼嗎?謝謝!

+3

這是'object_hit'分配給一個本地(for循環)在這裏'object_hit =&sphere_trans;'所以使用'object_hit'在它超出範圍後是未定義的行爲。 –

+0

@ShafikYaghmour我編輯了代碼,以便我不再創建局部變量。但我仍然有同樣的行爲。 – kaufmanu

回答

2

讓我們苗條下來一點......

Intersectable * object_hit; 
Sphere sphere_trans; 

// loop through spheres 
for(unsigned int j = 0; j < spheres.size(); j++) 
{ 
    ... 
    sphere_trans = Sphere(sphere.color, center3, sphere.getRadius()); 

    if(some condition) 
    { 
     object_hit = &sphere_trans; 
     ...  
    } 
} 

現在,當條件滿足時,在sphere_transobject_hit點。但是下一次循環,sphere_trans被分配一個新的對象。所以,當然,object_hit現在也指向新的對象,這可能不是你想要的。

最好的方法可能是使object_hit成爲一個對象而不是指針。或者只是將索引保存到數組中。

+0

不幸的是,我不能讓'object_hit'成爲一個對象(或者至少我不知道如何),因爲'Intersectable'是一個抽象類型。我不明白你的意思是「將索引保存到數組中」 – kaufmanu

+0

Intersectable是多態的,但是你的'Triangle'和'Sphere'對象實際上並不存在於任何永久形式中。你最好的選擇可能是複製構造它們到object_hit:'object_hit = new Sphere(sphere_trans);'關於內存泄漏和使用智能指針的所有常見警告適用於... – Roddy

+0

+1(實際上在我打了兩個小時後投票帽)我需要更多的睡眠,我完全錯過了問題的第二部分。 –

2

在此聲明:

object_hit = &sphere_trans; 

你分配object_hit到本地地址(for循環)變量。一旦您離開for循環,此pointer不再有效,並且取消引用pointer是未定義的行爲。

+0

謝謝!所以我在for循環前面添加了聲明「三角形三角形」和「球體sphere_trans」。但我仍然有同樣的行爲... – kaufmanu

+0

我已編輯帖子分別 – kaufmanu

+0

@StringerBell你可以創建一個小程序重現行爲,也許更具體地指定你期望的行爲是什麼。我暫時無法再看這個,但也許別人能夠找到其他可能存在的問題。另外一般情況下,如果您要更新您的問題,您應該原樣保留原文,並在最後附加任何更改或更新,否則新讀者會感到困惑。 –

相關問題