I had a working code that gave me the address of a mesh (if i'm correct):
MyMesh &mesh = glWidget->mesh();
Now I want if thingie to assign different mesh adresses. One is mesh() first function and another function mesh(int): How is this done?
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,...);
References must be bound to an object at initialization ... you cannot have a default-initialized or zero-initialized reference. So code like:
MyMesh &mesh;
where mesh
is a non-constant l-value reference to a Mesh
object, is inherently ill-formed. At the point of declaration, you must bind the non-constant reference to a valid memory-addressable object.
If your case is simple enough that meshNum
is constrained, you can use the ?:
operator:
MyMesh &mesh = (meshNum == 0) ? glWidget->mesh() : glWidget->mesh(0);
Otherwise, you need a pointer since references must be initializated at the definition point, and cannot be reseated to refer to anything else.
MyMesh *mesh = 0;
if( meshNum == 0 ) {
mesh = &glWidget->mesh();
} else if ( meshNum == 1 ){
mesh = &glWidget->mesh(0);
}
function( *mesh, ... );
References are valid at all times in a well behaved program, so no, you cannot do that. However, why not just:
if(meshNum != 0 && meshNum != 1)
return;
function((meshNum == 0) ? glWidget->mesh() : glWidget->mesh(0));
Or you could just use a pointer and deference it later:
MyMesh *mesh = 0;
if(meshNum==0) {
mesh = &glWidget->mesh();
}
else if (meshNum==1) {
mesh = &glWidget->mesh(0);
}
else {
return;
}
function(*mesh);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.