【问题标题】:How to pass a bool variable by reference in a non-bool function?如何在非布尔函数中通过引用传递布尔变量?
【发布时间】:2016-03-31 04:36:31
【问题描述】:

我查看了at how to pass a bool by reference,但该函数返回了其中的布尔值。我也看了here on stack overflow,但评论者的建议并没有改善我的情况。所以,

我有一个函数:

myTreeNode* search_tree(myTreeNode *test_irater, char p_test, bool &flag)

这显然会返回 myTreeNode* 类型。我还有一个变量bool flag,我想在函数内更改它的值。但是,当我尝试通过引用传递布尔值时,我收到一条错误消息

错误:“bool&”类型的非常量引用的初始化无效 来自 'bool*' 类型的右值|

如何在不返回布尔值的情况下通过引用传递布尔值?如果相关的话,我正在使用最新版本的 CodeBlocks。

编辑:代码

myTreeNode* search_tree(myTreeNode *test_irater, char p_test, bool &flag)
{
    switch(p_test) 
    {
    case 'a':
        if (test_irater->childA == NULL)
            flag = false;
        else {
            test_irater = test_irater->childA;
            flag = true;
        }
        break;
    case 't':
        if (test_irater->childT == NULL)
            flag = false;
        else {
            test_irater = test_irater->childT;
            flag = true;
        }
        break;
    case 'c':
        if (test_irater->childC == NULL)
            flag = false;
        else {
            test_irater = test_irater->childC;
            flag = true;
        }
        break;
    case 'g':
        if (test_irater->childG == NULL)
            flag = false;
        else {
            test_irater = test_irater->childG;
            flag = true;
        }
        break;
    }
    return test_irater;
}

像这样称呼:

test_irater = search_tree(test_irater, p_test, &flag); 

【问题讨论】:

  • 请显示产生此错误的代码。
  • 我编辑显示代码。

标签: c++


【解决方案1】:

你使用的是addressof(&)操作符,意思是&flag被转换成bool*

删除它,它应该可以工作:

test_irater = search_tree(test_irater, p_test, flag); 

【讨论】:

  • 该功能有效,但我认为它不会改变flag 的值。
  • @NickPredey 它会起作用的。如果您的函数签名需要引用,那么它将获得对您传入的参数的引用。这是一个演示:ideone.com/tDKK0s
  • 好的,我会重新评估我的功能,看看是否是问题所在。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-06-06
  • 1970-01-01
  • 2020-08-22
  • 2015-12-01
  • 2014-05-28
  • 2015-06-26
  • 2020-05-21
相关资源
最近更新 更多