gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 01:59:02 25 4
gpt4 key购买 nike

我有类 SphereTriangle,它们都是 Intersectable 的子类。 Intersectable 有一个公共(public)成员变量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 (...) 的值> 打印出来的颜色应该是一样的。但是,这不会发生。事实上,对于 color2 (...),我总是得到相同的输出。你能告诉我我做错了什么吗?谢谢!

最佳答案

让我们把它瘦一点...

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 成为对象而不是指针。或者只是将索引保存到数组中。

关于C++ 为什么同一个变量的值不同?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16573422/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com