带有 if 语句的指针(地址)
Pointer (address) with if statement
我有一个工作代码,给了我一个网格的地址(如果我是对的):
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);
相关文章:
- C++ 指针的内存地址和指向数组的内存地址如何相同?
- 在C++中打印指向不同基元数据类型的指针的内存地址
- 将地址分配给本地指针后,公共对象的变量将消失
- 为什么指针不写入类的地址?
- CUDA:统一内存和指针地址的更改
- 为什么 vector 的随机访问迭代器给出与指针不同的内存地址?
- 如何从绝对地址的 C 样式指针创建对C++对象的引用
- 当我在 C++ 中将派生类的指针分配给指针时,地址会更改
- 是否可以仅通过将分配的指针地址存储在C++中来分析内存?
- 如何在程序集函数中将元素数组作为参数传递时转发 ARM 寄存器的地址指针
- 如何使用构造函数初始化内存地址(指针变量)?
- 数组基础地址指针
- 如何在不使用返回的情况下从函数获取变量的地址(指针)
- 保存QWidgets的地址/指针
- C++ 读取内存地址/指针和偏移量
- 从存储在 CTreeCtrl 的 LPARAM 中的结构中检索地址/指针 (IXMLDOMNode*) - 不起作用
- 简单的C++地址/指针澄清
- 如何获取成员函数的地址指针
- 当“按引用传递”成为强制传递而不是按地址/指针传递时
- C++ 为什么不是同一个地址(指针)