【问题标题】:Pointer (address) with if statement带有 if 语句的指针(地址)
【发布时间】:2012-05-22 21:40:05
【问题描述】:

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

MyMesh &mesh = glWidget->mesh();

现在我想要 if 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,...);

【问题讨论】:

  • 这是一个引用,而不是一个指针。
  • 您在 glWidget 上调用的 mesh() 函数的签名是什么?它返回 MyMesh、MyMesh& 还是 MyMesh*?
  • if (meshNum > 1 || meshNum < 0) return; MyMesh& mesh(meshNum == 0 ? glWidget->mesh() : glWidget->mesh(0));
  • 谢谢大家!问题解决了!

标签: c++ pointers reference pointer-address


【解决方案1】:

如果您的案例足够简单以至于 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, ... );

【讨论】:

  • 一直是三元条件的粉丝!但是,你忘了关闭那个条件。
【解决方案2】:

引用必须在初始化时绑定到一个对象……你不能有一个默认初始化或零初始化的引用。所以代码如下:

MyMesh &mesh;

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

【讨论】:

    【解决方案3】:

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

    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);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-01-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多