我使用 gdb 找到了 seg 错误的确切行。它在 dequeue 函数中作为注释记录。
这是整个队列类。
dequeue()
当队列中有两个对象和哨兵时,我会在调用时出现故障。
template <typename T>
void Queue<T>::clear()
{
while(!isEmpty())
dequeue();
}
template <typename T>
void Queue<T>::enqueue(const T& x)
{
if(isEmpty())
{
Queue<T>* temp = new Queue<T>;
m_data = x;
m_next = temp;
return;
}
Queue<T>* temp = this;
while(temp->m_next != NULL)
{
temp = temp->m_next;
}
Queue<T>* node = new Queue<T>();
temp->m_data = x;
node->m_next = temp->m_next;
temp->m_next = node;
return;
}
template <typename T>
void Queue<T>::dequeue()
{
if(isEmpty())
return;
if(m_next != NULL)
{
Queue<T>* temp = m_next;
m_data = temp->m_data;
m_next = temp->m_next;
delete temp; //Seg fault here
}
return;
}
template <typename T>
const T& Queue<T>::front() const throw (int)
{
if(isEmpty())
throw 0;
return m_data;
}
template <typename T>
bool Queue<T>::isEmpty() const
{
return (m_next==NULL);
}
template <typename T>
int Queue<T>::size() const
{
int size = 0;
const Queue<T>* temp = this;
while(temp->m_next != NULL)
{
temp = temp->m_next;
size++;
}
return size;
}
抱歉,我以为我已经发布了 Queue 类:
template <typename T>
class Queue : public AbstractQueue<T> {
public:
Queue(){m_next = NULL;};
virtual void clear();
virtual void enqueue(const T& x);
virtual void dequeue();
virtual const T& front() const throw (int);
virtual bool isEmpty() const;
virtual int size() const;
~Queue(){
clear();
return;
};
private:
T m_data;
Queue* m_next;
};
它继承自这个类:
template < typename T >
class AbstractQueue
{
public:
// Purpose: clears the queue
// Postconditions: the queue is now empty
// -- PURE VIRTUAL
virtual void clear() = 0;
// Purpose: enqueue an element into the queue
// Parameters: x is the item to add to the queue
// Postconditions: x is now the element at the end of the queue,
// -- PURE VIRTUAL
virtual void enqueue(const T& x) = 0;
// Purpose: dequeues
// Postconditions: the element formerly at the front of the queue has
// been removed
// Dequeueing from an empty Queue produces no errors, queue remains empty.
// -- PURE VIRTUAL
virtual void dequeue() = 0;
// Purpose: looks at the front of the queue
// Returns: a reference to the element currently in front of the queue
// Exception: if the queue is currently empty, throw SOMETHING!!
// -- PURE VIRTUAL
virtual const T& front() const = 0;
// Purpose: Checks if a queue is empty
// Returns: 'true' if the queue is empty
// 'false' otherwise
// -- PURE VIRTUAL
virtual bool isEmpty() const = 0;
// Purpose: Returns the size of a queue.
// Returns: the number of elements in the Queue
// -- PURE VIRTUAL
virtual int size() const = 0;
// ----------------
// Purpose: Destructor
// -- VIRTUAL
virtual ~AbstractQueue() {};
};