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

Pointer (address) with if statement

本文关键字:地址 指针 if 语句 带有      更新时间:2023-10-16

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

MyMesh &mesh = glWidget->mesh();

现在我想让 thingie 分配不同的网格地址。一个是mesh()第一个函数,另一个是函数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, ... );

引用必须在初始化时绑定到对象...不能有缺省初始化或零初始化引用。 所以代码像:

MyMesh &mesh;

其中mesh是对Mesh对象的非常量 l 值引用,本质上是格式错误的。 在声明点,必须将非常量引用绑定到有效的内存可寻址对象。

引用在

运行良好的程序中始终有效,所以不,你不能这样做。 但是,为什么不只是:

if(meshNum != 0 && meshNum != 1)
    return;
function((meshNum == 0) ? glWidget->mesh() : glWidget->mesh(0));

或者你可以只使用指针并在以后尊重它:

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