C使用自己的类继承堆栈

前端之家收集整理的这篇文章主要介绍了C使用自己的类继承堆栈前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我试图创建自己的类(NodeWithMin)作为C中的堆栈元素,并创建一个继承它的新类(StackWithMin).我想我可以创建新的堆栈类,但是有一些问题初始化新类的新实例并使用它.有没有人对它有好主意?我在一个文件中写了所有类和main.谢谢.
#include <stack>

class NodeWithMin{
public:
    int value;
    int min;
    NodeWithMin(int v,int min){
        this->value = v;
        this->min = min;
    }
};

template<class NodeWithMin>
class StackWithMin : stack<NodeWithMin>{
public:
    typedef stack<NodeWithMin> super;
    void push(int value){
        int newMin = min(value,this->min());
        super::push(new NodeWithMin(value,newMin));
    };

    int min(){
        if(this->isEmpty()){
            return numeric_limits<int>::max();
        }else{
            super::peek().min;
        }
    };
};

int main(int argc,const char * argv[])
{
    StackWithMin<class NodeWithMin>* ss;
    ss = new StackWithMin<class NodeWithMin>();
}

解决方法

首先,我删除
using namespace std;

所以我可以限定std以消除歧义.

我注意到的第一个问题是这一行:

int newMin = min(value,this->min());

我的猜测是你试图使用min算法(因为堆栈不包含min函数):

#include <algorithm>
// snip
int newMin = std::min(value,this->min())

第二个问题是你没有堆栈< NodeWithMin>的实例,只有一个typedef.因此你需要像这样使用它:

typedef std::stack<NodeWithMin> super;
        super super_instance;
        void push(int value){
                int newMin = std::min(value,this->min());
                // Why are you using new? It would make
                // It more difficult to avoid memory leaks
                super_instance.push({value,newMin});
        };

第三个问题是stack没有名为isEmpty的成员函数,你的类也没有. stack也没有peek成员函数.

int min(){
                if(super_instance.empty()){
                        return std::numeric_limits<int>::max();
                }else{
                        return super_instance.top().min;
                }
        };

现在它将编译:

int main(int argc,const char * argv[])
{
    StackWithMin<class NodeWithMin>* ss;
    ss = new StackWithMin<class NodeWithMin>();
    ss->push(42);
    delete ss;
}

我没有费心检查逻辑错误.

猜你在找的C&C++相关文章