【发布时间】: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->push(element); // Unhandled Exception。想想在push内部调用push而不使用终止条件来停止递归的效果。
标签: c++