【问题标题】:I'm having trouble with using std::stack to retrieve the values from a recursive function我在使用 std::stack 从递归函数中检索值时遇到问题
【发布时间】:2011-02-15 14:12:43
【问题描述】:

感谢我在这篇文章中得到的帮助:

How do I use "this" in a member function?

我有一个简洁的递归函数以后缀顺序遍历树:

void Node::postfix()
{
        if (left != __nullptr) { left->postfix(); } 
        if (right != __nullptr) { right->postfix(); } 
                cout<<cargo<<"\n"; 
        return;
};

现在我需要评估返回的值和运算符。我的问题是如何检索

他们。我尝试了 std::stack:

#include <stack> 
stack <char*> s;
void Node::postfix()
{
        if (left != __nullptr) { left->postfix(); } 
        if (right != __nullptr) { right->postfix(); } 
        s.push(cargo);
        return;
};

但是当我尝试在 main() 中访问它时

while (!s.empty())
{
    cout<<s.top<<"\n";
    s.pop;
}

我得到了错误:

'std::stack<_ty>::top': 函数调用缺少参数列表;使用 '&std::stack<_ty>::top' 创建

指向成员的指针'

我被困住了。

另一个问题很快就会跟进。

【问题讨论】:

    标签: c++ recursion stack


    【解决方案1】:

    它们是成员函数

    s.top()
    s.pop()
         ^ need parentheses to call a function
    

    当它说“函数调用缺少参数列表”时,这就是错误的含义。参数列表(在这种情况下是空的,因为函数没有参数)和括号丢失。

    【讨论】:

    • 该死!就如此容易。感谢所有的答案。
    【解决方案2】:

    top 和 pop 是函数,而不是成员变量。你应该写

    s.top();
    s.pop();
    

    【讨论】:

      【解决方案3】:

      top()std::stack 中的成员函数,而不是成员变量。所以你在调用top时需要括号

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2012-09-21
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-12-20
        • 1970-01-01
        • 2019-12-24
        • 1970-01-01
        相关资源
        最近更新 更多