gpt4 book ai didi

c++ - 为什么我需要声明 underflow_error

转载 作者:太空宇宙 更新时间:2023-11-04 16:21:13 25 4
gpt4 key购买 nike

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

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时。

关于c++ - 为什么我需要声明 underflow_error,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16661206/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com