【发布时间】:2021-04-05 04:02:36
【问题描述】:
当我构建这段代码时,它不会打印出任何东西。这段代码有什么问题,我参考了网上的一段代码,它使用了一个结构来声明队列。但我只是想使用类。使用类的对象有什么问题吗?这段代码还有哪些问题?
#include<bits/stdc++.h>
using namespace std;
class Queue{
public:
int front, rear, size;
unsigned capacity;
int* array;
};
Queue* createQueue(unsigned capacity){
Queue* queue = new Queue;
queue->front = queue->size = 0;
queue->capacity = capacity;
queue->rear = queue->capacity-1;
queue->array = new int[queue->capacity];
}
int isEmpty(Queue* queue){
return (queue->size==0);
}
int isFull(Queue* queue){
return (queue->size==queue->capacity);
}
void enqueue(Queue* queue, int item){
if(isFull(queue)){
return;
}else{
queue->rear = (queue->rear+1)%queue->capacity;
queue->size = queue->size+1;
queue->array[queue->rear] = item;
cout << item << " enqueued to queue\n";
}
}
int dequeue(Queue* queue){
if(isEmpty(queue)){
return NULL;
}else{
int temp = queue->array[queue->front];
queue->front = (queue->front+1)%queue->capacity;
queue->size = queue->size-1;
return temp;
}
}
int front(Queue* queue){
if(isEmpty(queue)){
return 0;
}else{
return queue->array[queue->front];
}
}
int rear(Queue* queue){
if(isEmpty(queue)){
return NULL;
}else{
return queue->array[queue->rear];
}
}
int main(){
Queue queue;
Queue* ptr = &queue;
enqueue(ptr, 10);
}
【问题讨论】:
-
你打算用
createQueue做点什么吗?我很大的暗示,有些事情出轨了,这个函数似乎注定要...... 创建一个队列,但从未在任何这段代码中使用过。除了该函数中的错误(它从不返回值),现在Queue queue;默认构造一个Queue,它从不初始化任何成员变量以确定值。因此,像isFull中的return (queue->size==queue->capacity)这样的后续表达式依赖于不确定的值,并调用未定义的行为。从字面上看,这看起来像是一个糟糕的 C 队列端口。 -
感谢您的评论。我错过了 createQueue 来初始化成员的功能。非常感谢。
-
是否有一些与 C 库兼容的要求,或者是否有任何其他原因不制作除
main和createQueue成员函数之外的所有函数并移动createQueue的逻辑给构造函数?
标签: c++ algorithm data-structures queue