【问题标题】:Variable passed-by-reference is changed in function scope but not in main scope通过引用传递的变量在函数范围内更改,但在主范围内未更改
【发布时间】:2021-11-20 15:58:59
【问题描述】:

我正在尝试将给定的向量网格更改为高度图,我通过引用一个函数来传递一个顶点向量,该函数应该计算每个顶点的高度并更改它。但是,在主范围内打印新顶点的高度时,全部为0,而如果我在计算它们之后打印顶点的高度,我会得到正确的结果。

int main(){
 std::vector<glm::vec3> vertinfo = generate_grid(4, 4, 2.0f, 2.0f); //generates the grid
 generate_randomheightmap(vertinfo); //SHOULD modify the height of the vertices
//printing the y value of any of the vertices here will result in 0 (the unchanged value)
...
}
void generate_randomheightmap(std::vector<glm::vec3>& base, uint32_t layers){
 for (glm::vec3 vertex : base){
  vertex.y += vertex.x * vertex.z;
  //printing the y value of the vertex here will result in the correct calculated value
 }
}

这不是因为 vec3 对象本身被复制而向量没有被复制吗? 如果我必须将 vec3 更改为 vec3 指针,那将非常烦人

【问题讨论】:

  • 缺少参考:for (glm::vec3&amp; vertex : base).

标签: c++ pass-by-reference


【解决方案1】:

问题不在于函数的引用传递,而在于for 循环。它应该使用对向量元素的引用:

for (glm::vec3& vertex : base)

【讨论】:

    猜你喜欢
    • 2019-01-10
    • 2013-12-08
    • 1970-01-01
    • 1970-01-01
    • 2015-12-23
    • 2014-06-08
    • 2011-09-01
    • 2021-10-04
    • 2020-09-25
    相关资源
    最近更新 更多