C++ - 在 for 循环中没有正确设置值

标签 c++ loops setvalue

我正在尝试为三角形类的三个对象设置第二个和第三个角的值。如果明确地完成,这看起来像这样:

triangle_mesh[0].set_vector_point2(vector_anchors[1]);
triangle_mesh[1].set_vector_point3(vector_anchors[1]);
triangle_mesh[1].set_vector_point2(vector_anchors[2]);
triangle_mesh[2].set_vector_point3(vector_anchors[2]);
triangle_mesh[2].set_vector_point2(vector_anchors[3]);
triangle_mesh[0].set_vector_point3(vector_anchors[3]);

有效!打印这些三角形,我得到(注意第一个角已经设置 - 这不是问题):

triangle0 is ( 0, 0, -1) (1, 0, 0) (-0.5, -0.866025, 0)
triangle1 is ( 0, 0, -1) (-0.5, 0.866025, 0) (1, 0, 0)
triangle2 is ( 0, 0, -1) (-0.5, -0.866025, 0) (-0.5, 0.866025, 0)

不过,首先,这很丑陋,其次,它必须推广到我要设置三个以上三角形的情况。我的代码是:

for (int longitude = 0; longitude < num_longitudes; longitude++){
  SurfaceVector current_anchor = vector_anchors[1 + longitude];
    triangle_mesh[longitude].set_vector_point2(current_anchor);
    triangle_mesh[(longitude + 1) % num_longitudes].set_vector_point3(current_anchor);
}

*注意num_longitudes 是 3*

我已经检查了我能想到的一切,但现在当我打印出我的三角形时,我得到:

triangle0 is ( 0, 0, -1) (-0.5, -0.866025, 0) (-0.5, -0.866025, 0)
triangle1 is ( 0, 0, -1) (-0.5, -0.866025, 0) (-0.5, -0.866025, 0)
triangle2 is ( 0, 0, -1) (-0.5, -0.866025, 0) (-0.5, -0.866025, 0)

有谁知道哪里出了问题?!

编辑

三角形上的 vector_point 变量是指针,设置如下:

void set_vector_point1(SurfaceVector vector_point) { vector_point1 = &vector_point; }

最佳答案

这就是你的问题:

void set_vector_point1(SurfaceVector vector_point) { vector_point1 = &vector_point; }

您正指向一个临时的(vector_point 在函数调用完成后不复存在)。更改它以便正确复制 SurfaceVector

关于C++ - 在 for 循环中没有正确设置值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9787068/

相关文章:

javascript - Greasemonkey 无法执行 GM_setValue()

python - 如何使用 Python 在一个命令中追加和设置值?

c++ - 如何在 OpenGL 中使用框选择有效地选择对象

c++ - CSimpleString 中的遗留 MFC 跨线程异常

Python 语音识别库 - 总是在听?

excel - 循环不会停止,导致溢出

c++ - lvlc-qt 缺少编译错误

c++ - 异常抛出异常

c - 使用 EOF 循环打印最小值和最大值

wpf - 依赖属性 SetValue() 和 SetCurrentValue() 之间有什么区别