为什么我需要声明underflow_error

Why do i need to declare underflow_error

本文关键字:underflow error 声明 为什么      更新时间:2023-10-16

在下面的代码中,我得到错误

Stack.cpp: In member function ‘T* Stack<T>::pop()’: Stack.cpp:53: error: there are no arguments to ‘underflow_error’ that depend on a template parameter, so a declaration of ‘underflow_error’ must be available

声明class underflow_error;的理由是什么?

#include <iostream>
using namespace std;
template <class T>
class Stack
{
public:
    Stack(): head(NULL) {};
    ~Stack();
    void push(T *);
    T* pop();
protected:
    class Element {
    public:
            Element(Element * next_, T * data_):next(next_), data(data_) {}
            Element * getNext() const { return next; }
            T * value() const {return data;}
    private:
            Element * next;
            T * data;
    };
    Element * head;
};
template <class T>
Stack<T>::~Stack()
{
    while(head)
    {
            Element * next = head->getNext();
            delete head;
            head = next;
      }
 }
template <class T>
T * Stack<T>::pop()
{
    Element *popElement = head;
    T * retData;
    if(head == NULL)
            throw underflow_error("stack is empty");
    retData = head->value();
    head = head->getNext();
    delete popElement;
    return retData;
}

你必须添加

#include <stdexcept>

使用underflow_error

相关文章: