【发布时间】:2021-02-06 05:06:35
【问题描述】:
我有一个类模板“Stack”,用于制作堆栈数据结构。另一个类模板“specialStack”(公开继承“stack”类)用于在 O(1) 时间复杂度内从堆栈中获取最小元素 - getMin() 可以完成这项工作。
我从基类继承 isEmpty() 时出错。它显示 isEmpty() 未声明的标识符(如您在下面的屏幕截图中所见)。我发现要解决这个问题,我们必须再次覆盖派生类中的函数,但如果我们在基类中有很多函数,则不可能覆盖所有函数。我还尝试了第二种方法,通过在派生类中使用 stack::isEmpty() 来解决这个问题,但现在它又给了我一堆错误。
这是我的代码:-
#include<iostream>
using namespace std;
template<class T>
class stack {
static const int max = 100;
int arr[max];
int top = -1, size = max;
public:
void push(T x);
T pop();
int isEmpty();
T topElement();
};
template<class T>
int stack<T>::isEmpty() {
if (top == -1) return 1;
return 0;
}
template<class T>
void stack<T>::push(T x) {
if (top!=size) arr[++top] = x;
}
template<class T>
T stack<T>::pop() {
if (top != -1)
{
return arr[top--];
}
}
template<class T>
T stack<T>::topElement() {
if (top != -1) return arr[top];
}
template<class T>
class specialStack : public stack<T> {
stack<T>min;
public:
void push(T x);
T pop();
T getMin();
};
template<class T>
void specialStack<T>::push(T x) {
if (isEmpty()) {
min.push(x);
stack::push(x);
}
else {
T y = min.topElement();
if (x < y)
{
stack::push(x);
min.push(x);
}
else {
stack::push(x);
min.push(y);
}
}
}
template<class T>
T specialStack<T>::pop() {
if (true)
{
min.pop();
stack::pop();
}
}
template<class T>
T specialStack<T>::getMin() {
return min.topElement();
}
int main() {
specialStack<int>st;
st.push(1);
st.push(2);
st.push(3);
st.push(4);
st.push(5);
st.push(6);
cout << st.getMin();
}
这是错误截图:
【问题讨论】:
-
试试
stack<T>::isEmpty() -
using Base = stack<T>;和Base::isEmpty()(Base::push(x)等)。
标签: c++ c++11 inheritance class-template