【问题标题】:Inheriting from the stack class从堆栈类继承
【发布时间】:2016-10-29 20:20:25
【问题描述】:

大家好,我不知道如何正确命名。我的查询是我所做的堆栈的实现。在代码中,我假设我们可以使用 this->push() 或 this->pop() 但需要范围运算符(stack::push)。我不明白为什么?

#include <iostream>
#include <stack>


template <class T >
class SpecialStack : std::stack<T>
{

public:

    SpecialStack() : isEmpty(true) {};

    void push(T element)
    {
        if (!isEmpty)
        {
            T LastMin = min_stack.top();

            if (element < LastMin)
            {
                min_stack.push(element);
            }
            else
            {
                min_stack.push(LastMin);
            }
        }else
        {
            min_stack.push(element);

        }
        stack::push(element); // works
        //this->push(element); // Unhandled Exception
    }

    T pop()
    {
        min_stack.pop();
        T out = stack::top();
        stack::pop();
        return out;

    }

    T getMin()
    {
        return min_stack.top();

    }
private:

    std::stack<T> min_stack;

    bool isEmpty;

};


int main()
{
    SpecialStack<int> s;
    s.push(3);
    s.push(2);
    s.push(1);
    s.push(5);
    s.push(6);
    //cout << s.getMin() << endl;

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

    std::cout << s.getMin() << std::endl;

    system("pause");




}

【问题讨论】:

  • 你的类“is-a”还是“has-a”堆栈?我认为您不想既继承自 std::stack 又拥有 std::stack 类型的成员。
  • 错误信息是什么?顺便说一句,您的 isEmpty 永远不会更新为 false。
  • 您发布的代码无法编译。
  • 您是否打算使用默认继承说明符?由于 std::stack 是一个模板类,我猜它是私有继承。
  • this-&gt;push(element); // Unhandled Exception。想想在 push 内部调用 push 而不使用终止条件来停止递归的效果。

标签: c++


【解决方案1】:
void push(T element) {
   ...
   this->push(element);
}

最后一行递归调用你的push 函数。由于进程永远不会终止,因此您会遇到堆栈溢出异常。

stack::push 是告诉编译器您要从父类调用实现的正确方法。

【讨论】:

  • 是的,你是对的,出于某种原因,我认为这将引用父类。谢谢!
猜你喜欢
  • 1970-01-01
  • 2012-03-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-10-21
  • 1970-01-01
  • 2023-03-27
相关资源
最近更新 更多