C ++为什么同一个变量的值不同?

时间:2013-05-15 19:28:17

标签: c++ class pointers

我的课程SphereTriangle都是Intersectable的子类。 Intersectable有一个公共成员变量colour。请考虑以下代码片段:

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 (...)的相同输出。你能告诉我我做错了什么吗?谢谢!

2 个答案:

答案 0 :(得分:2)

在此声明中:

object_hit = &sphere_trans;

您正在将object_hit分配给本地(到for循环)变量的地址。离开for循环后,此pointer不再有效,并且取消引用pointer是未定义的行为。

答案 1 :(得分: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;
        ...    
    }
}

现在,当条件满足时,object_hit指向sphere_trans。但是下次循环时,会为sphere_trans分配一个新对象。所以,当然,object_hit现在也指向新对象,这可能不是你想要的。

最好的方法可能是使object_hit成为对象而不是指针。或者只是将索引保存到数组中。