C&C++   发布时间:2022-04-03  发布网站:大佬教程  code.js-code.com
大佬教程收集整理的这篇文章主要介绍了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;

@R_111_9447@限定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使用自己的类继承堆栈所遇到的程序开发问题。

如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。