通过参考不工作 [英] pass by reference not working
问题描述
试图实现一个函数来改变菜单上的状态,但是当进入函数时我的引用丢失了。
void gotoLowerlevel (菜单*项目)
{
if(item-> chld!= 0x00){
item = item-> chld;
函数调用以这种方式完成
currentState是一个指向结构体Menu的指针
pre code> case ENTER:
if(cnsle-> inMenuFlag == 0)
{
cnsle-> inMenuFlag = 1;
cnsle-> currentState = cnsle-> root;
gotoLowerlevel(cnsle-> currentState);
displayMenu(cnsle-> currentState,& cnsle-> display);
}
我不知道为什么这不起作用。任何想法......
我的偏好是最后一个选项,可以修改 其他人已经解释了如何传递引用。代码我的首选解决方案是: in trying to implement a function to change state on menu but my reference is lost when is enters the function the function call is done in this manner
currentState is a pointer to struct Menu i have no idea why this isn't working. Any ideas..?? My preference would be the last option, as this makes it clear when reading the calling code that Others have explained how to pass a reference. Code for my preferred solutions is:
这篇关于通过参考不工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋! cnsle-> currentState
,您需要:
cnsle-> currentState
的引用(即将方法签名更改为 Menu ** itemptr
,将调用参数更改为& cnsle-> currentState
)
gotoLowerLevel
返回新值并赋值: cnsle-> currentState = gotoLowerLevel(cnsle-> ; currentState)
currentState
的代码。
$ b $ pre $ 菜单* gotoLowerlevel(Menu * item)
{
if( item-> chld!= 0x00){
item = item-> chld;
}
退货项目;
}
/ * .... * /
cnsle-> currentState = gotoLowerlevel(cnsle-> currentState);
void gotoLowerlevel(Menu *item)
{
if (item->chld != 0x00){
item = item->chld;
}
}
case ENTER:
if (cnsle->inMenuFlag == 0)
{
cnsle->inMenuFlag = 1;
cnsle->currentState = cnsle->root;
gotoLowerlevel(cnsle->currentState);
displayMenu(cnsle->currentState,&cnsle->display);
}
item
in gotoLowerLevel
is a local variable even if it is a reference to an object elsewhere. To modify cnsle->currentState
you need to either:
cnsle
cnsle->currentState
(that is change the method signature to Menu ** itemptr
and the call parameter to &cnsle->currentState
)gotoLowerLevel
and assign it: cnsle->currentState = gotoLowerLevel(cnsle->currentState)
currentState
may be modified.Menu* gotoLowerlevel(Menu *item)
{
if (item->chld != 0x00) {
item = item->chld;
}
return item;
}
/* .... */
cnsle->currentState = gotoLowerlevel(cnsle->currentState);