通过引用传递不会更改变量

问题描述:

我正在尝试实现一个功能来更改菜单的状态,但是当它离开该功能时,我的引用会丢失:

I am trying to implement a function to change state of the menu, but my reference is lost when it leaves the function:

void gotoLowerlevel(Menu *item)
{
    if (item->chld != 0x00) {
        item = item->chld;
    }
}

以这种方式完成函数调用(currentState是指向struct Menu的指针):

The function call is done in this manner (currentState is a pointer to struct Menu):

case ENTER:
    if (cnsle->inMenuFlag == 0)
    {
        cnsle->inMenuFlag = 1;
        cnsle->currentState = cnsle->root;
        gotoLowerlevel(cnsle->currentState);
        displayMenu(cnsle->currentState,&cnsle->display);
    }

我不知道为什么这不起作用.有什么想法吗?

I have no idea why this isn't working. Any ideas?

item是局部变量,即使它是对其他对象的引用.要修改cnsle->currentState,您需要执行以下操作之一:

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的引用(即将方法签名更改为Menu ** itemptr,并将调用参数更改为&cnsle->currentState)
  • 或从gotoLowerLevel返回新值并分配给它:cnsle->currentState = gotoLowerLevel(cnsle->currentState)
  • pass in cnsle
  • pass in a reference to cnsle->currentState (that is change the method signature to Menu ** itemptr and the call parameter to &cnsle->currentState)
  • or return the new value from gotoLowerLevel and assign it: cnsle->currentState = gotoLowerLevel(cnsle->currentState)

我的偏好设置是最后一个选项,因为在读取调用代码时可以清楚地看到currentState可以被修改.

My preference would be the last option, as this makes it clear when reading the calling code that currentState may be modified.

其他人已经说明了如何传递参考.我的首选解决方案的代码是:

Others have explained how to pass a reference. Code for my preferred solutions is:

Menu* gotoLowerlevel(Menu *item)
{
    if (item->chld != 0x00) {
        item = item->chld;
    }
    return item;
}

/* .... */
cnsle->currentState = gotoLowerlevel(cnsle->currentState);