c++ - 传递对指针的引用

标签 c++ pointers reference overloading private

我在使用一个私有(private)递归辅助函数时遇到问题,我在指针中传递了一个引用。我收到一条错误消息

“没有重载函数“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
        }
};

最佳答案

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

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
}

关于c++ - 传递对指针的引用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27097440/

相关文章:

.net - VB.NET 2K8 : How to make all imports visible within a class?

pdf - 如何在 Puppeteer 中添加所有相对 URL 的绝对路径(本地 html 文件应从网络加载图像以生成 PDF)

algorithm - 关于 A* 算法的可信引用

c++ - 指针 "gets informed"如何知道指向对象的哪一部分可以访问?

c++ - OpenGL Stenciling,将引用与写入的值分开?

c++ - 以编程方式检查字节顺序

c++ - 指针 vector ,继承

c++ - 返回引用和返回值

c++ - 错误 : expected type-specifier before Class

c++ - 对我的 BFS tile 类中的引用和指针感到困惑