2013-05-21 78 views
0

宣布在下面的代码,我得到错误为什么需要underflow_error

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; 
} 
+2

您不应该在头文件中使用using指令('using namespace X')。 –

回答

5

您必须添加

#include <stdexcept> 

当您使用underflow_error

+0

奇怪的是,看着http://www.cplusplus.com/reference/stdexcept/underflow_error/,它并没有说明stdexcept – Jimm

+0

@Jimm中的underflow_error声明存在于广告图片的正上方,您将看到:参考> stdexcept> underflow_error – taocp

+0

谢谢!!!我错过了。 – Jimm