gpt4 book ai didi

c++ - 带有 if 语句的指针(地址)

转载 作者:行者123 更新时间:2023-11-27 23:23:58 25 4
gpt4 key购买 nike

我有一个工作代码,它给了我一个网格的地址(如果我是正确的话):

MyMesh &mesh = glWidget->mesh();

现在我想要 if thingie 分配不同的网格地址。一个是mesh() first function,另一个是mesh(int)函数:这是怎么做到的?

 MyMesh &mesh;  //error here: need to be initialized

if(meshNum==0){
mesh = glWidget->mesh();
}
else if (meshNum==1){
mesh = glWidget->mesh(0);
}
else{
return;
}

//mesh used in functions...
function(mesh,...);

最佳答案

如果您的情况足够简单以至于 meshNum 受到约束,您可以使用 ?: 运算符:

MyMesh &mesh = (meshNum == 0) ? glWidget->mesh() : glWidget->mesh(0);

否则,您需要一个指针,因为引用必须在定义点处初始化,并且不能重新定位以引用其他任何内容。

MyMesh *mesh = 0;
if( meshNum == 0 ) {
mesh = &glWidget->mesh();
} else if ( meshNum == 1 ){
mesh = &glWidget->mesh(0);
}

function( *mesh, ... );

关于c++ - 带有 if 语句的指针(地址),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10710586/

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