2013-05-15 53 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你可以创建一个小程序重现行为,也许更具体地指定你期望的行为是什么。我暂时无法再看这个,但也许别人能够找到其他可能存在的问题。另外一般情况下,如果您要更新您的问题,您应该原样保留原文,并在最后附加任何更改或更新,否则新读者会感到困惑。 –

相关问题