【问题标题】:Passing references to pointers传递对指针的引用
【发布时间】:2014-11-24 03:29:48
【问题描述】:

我遇到了一个私有递归辅助函数的问题,我在指针中传递了一个引用。我收到一条错误消息,提示

“没有重载函数“insertSymbol”的实例与参数列表匹配。参数类型为:(String, Expression *)”

我想我对传递引用有误解。有人可以帮帮我吗?

struct ExpressionTree {
    private:
        Expression* root;

        bool insertSymbol(String& symbol, Expression*& root) {
            if (root == nullptr) { // base case
                root = new Expression(symbol);
                return true;
            }

            if ((*(*root).getSymbol()).c_str()[0] == '~') { 
                return insertSymbol(symbol, (*root).getLeftChild()); // Error occurs here
            }
        }

    public:
        ExpressionTree(void) {
            root = 0x00;
        }

        // returns true if insert was successful, otherwise returns false
        bool insertSymbol(String& symbol) {
            if (symbol.size == 0) return false;
            return insertSymbol(symbol, root); // Calls recursive helper function
        }
};

【问题讨论】:

  • 我们不知道getLeftChild 是什么或它返回什么。但看起来您正在尝试将引用绑定到临时文件,这是不允许的。

标签: c++ pointers reference overloading private


【解决方案1】:

您不能将引用绑定到临时对象。一种可能的解决方法是:

bool insertSymbol(String& symbol, Expression*& root) {
    if (root == nullptr) { // base case
        root = new Expression(symbol);
        return true;
    }
    return insertSymbolHelper(symbol, root);
}

bool insertSymbolHelper(String& symbol, Expression* root) {
    if ((*(*root).getSymbol()).c_str()[0] == '~') { 
        return insertSymbolHelper(symbol, (*root).getLeftChild()); // Error occurs here
    }
    // rest of code goes here
}

【讨论】:

  • 虽然我没有看到足够多的代码来确定,但我敢打赌这个修复会导致在第二次调用 insertSymbol 时指针取消引用无效。
  • @BenjaminLindley 我假设getLeftChild 不能返回NULL。如果可以,则需要进行更多更改。 (也许getLeftChild 应该返回一个引用?)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-01-13
  • 2010-10-23
  • 2016-05-02
  • 2013-12-24
  • 2015-02-11
  • 1970-01-01
相关资源
最近更新 更多