通过参考不工作 [英] pass by reference not working

查看:102
本文介绍了通过参考不工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

试图实现一个函数来改变菜单上的状态,但是当进入函数时我的引用丢失了。

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

我不知道为什么这不起作用。任何想法......

解决方案

c> gotoLowerLevel 是一个局部变量,即使它是对其他对象的引用。要修改 cnsle-> currentState ,您需要:


  • code> cnsle

  • 传递对 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);


in trying to implement a function to change state on menu but my reference is lost when is enters the function

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

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 in gotoLowerLevel is a local variable even if it is a reference to an object elsewhere. To modify cnsle->currentState you need to either:

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

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

这篇关于通过参考不工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆