为什么在C ++中,模板类型的“ stack”类的isEmpty不继承到模板类型的派生类“ specialStack”中?

问题描述

我有一个用于创建堆栈数据结构的类模板“ 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();
}

这是错误屏幕截图:

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)