我的问题:为什么我的程序在出列(实际上是删除)我在队列中排队的唯一节点时出现运行时错误?我在相应的函数中写了一些调试语句,指出该行有问题
delete front;
当程序执行到该行时,它想退出,因为它没有回应我。我试过了
if(front) delete front;
但无济于事。我试图在谷歌上找到答案,但没有得出任何令人满意的结果。这很奇怪。几年来我一直在处理 OOP,但这对我来说是第一次。这是我的代码:
================================ Queue.cpp ============ ===========================
#include <iostream>
#include "Queue.h"
using namespace std;
Queue::Queue()
{
QueueNode * front = NULL;
QueueNode * rear = NULL;
}
Queue::~Queue()
{
while(rear) dequeue();
}
void Queue::enqueue(int row, int col)
{
// create the child state:
QueueNode * newNode;
newNode = new QueueNode;
// write in child state's coordinates:
newNode->row = row;
newNode->col = col;
// enqueue the child state:
if(!front) // if empty, new is front
{
// first node = front and back
front = newNode;
rear = newNode;
}
else // not the first node:
{
newNode->next = rear; // new points to back
rear = newNode; // new is the back
}
}
void Queue::dequeue()
{
cout << "\nHere\n";
delete front;
cout << "\nHere 2\n";
front = rear;
cout << "\nHere 3\n";
while(front->next) front = front->next;
cout << "\nHere 4\n";
}
================================= Queue.h =========== ============================
#ifndef QUEUE_H
#define QUEUE_H
class Queue
{
public:
struct QueueNode
{
// numbers:
int row;
int col;
QueueNode * next;
};
QueueNode * front;
QueueNode * rear;
Queue();
~Queue();
void enqueue(int, int);
void dequeue();
//void traverse(); // scan for repetition of location.
//void displayQueue() const;
};
#endif
注意:
1) 我没有包含主要驱动程序的代码,因为这需要用大量制表符替换 4 个空格。
2) 我只入队了一个队列节点。
3) 我已将队列类中的所有内容公开,因为我迫切希望找出问题所在。我打算暂时保持这种状态。
4) 这是我第一次在 StackOverflow.com 上提问,所以如果我做错了什么,那么我还在学习。
5) 我使用的是 Visual C++ 2008 Express Edition。
同样,我的疑问:为什么程序在删除队列中的唯一节点时出现运行时错误?
最佳答案
错误在这里
Queue::Queue()
{
QueueNode * front = NULL;
QueueNode * rear = NULL;
}
应该是
Queue::Queue()
{
front = NULL;
rear = NULL;
}
在您的版本中,您的构造函数中有两个局部 变量,它们恰好与类中的变量同名。所以你的构造函数根本没有初始化你的类。
顺便说一句,你应该养成使用初始化列表的习惯
Queue::Queue() : front(NULL), rear(NULL)
{
}
要是这个错误不会发生就好了
顺便说一句,这是一个很好的问题。
关于c++ - 无法使 C++ 中的节点出队,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19075751/