在下面的代码中,我收到错误
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;
}
答案 0 :(得分:5)
你必须添加
#include <stdexcept>
使用underflow_error
。