c++ - 使用类模板模拟 FIFO 的 C++ 程序,出队时返回值 3221225477
问题描述
我目前正在大学学习我的第二门 C++ 面向对象编程课程,所以我的代码中可能会有不好的编程习惯和一般错误,所以,如果你看到任何错误,请指出它们。我总是乐于学习。
我目前有一个关于 C++ 模板的任务,我必须创建一个程序,该程序具有一个模拟 FIFO(先进先出)队列的类,使用不同的类作为模板类型(队列<人类>人类队列)。
队列.h
#ifndef QUEUE_H
#define QUEUE_H
#include "human.h"
template<class T>
class Queue : public Human{
public:
Queue(int = 5);
~Queue();
void enqueue(T);
T dequeue();
void PrintQueue();
private:
T* array;
int size, index;
};
#endif
队列.cpp
#include <iostream>
#include "queue.h"
using namespace std;
template<class T>
Queue<T>::Queue(int s){
array = new T[s];
size = s;
index = 0;
}
template<class T>
Queue<T>::~Queue(){
delete [] array;
}
// Add object to end of array
template<class T>
void Queue<T>::enqueue(T obj){
if(index == size){
cout << "Rinda ir pilna, nevar pievienot elementu!" << endl; // Array full, can't add any more objects
return;}
else{
array[index] = obj;
index++;}
}
// Remove object from start of array and shift the whole array by 1 position
template<class T>
T Queue<T>::dequeue(){
for(int i = 0; i < size; i++){
array[i] = array[i + 1];
}
index--;
}
template<class T>
void Queue<T>::PrintQueue(){
for(int i = 0; i < index; i++){
cout << i + 1 << ". ";
array[i].PrintHuman();
}
}
主文件
#include <iostream>
#include "human.h"
#include "queue.h"
#include "queue.cpp"
using namespace std;
int main(){
Queue<Human> HumanQueue(3);
Human a("Janis", 1.86, 76);
Human b("Peteris", 1.76, 69);
Human c("Arturs", 1.79, 75);
Human d("Aleksis", 1.81, 78);
cout << "Elementu rinda" << endl; // Element queue
HumanQueue.enqueue(a);
HumanQueue.enqueue(b);
HumanQueue.PrintQueue();
cout << "\n//Pievienojam elementu rindai//" << endl; // Add element to queue
HumanQueue.enqueue(c);
HumanQueue.PrintQueue();
cout << "\n//Meginam pievienot vel 1 elementu rindai//" << endl; // Trying to add one more element to queue, should return, that queue is full
HumanQueue.enqueue(d);
HumanQueue.PrintQueue();
cout << "\n//Iznemam 2 elementus no rindas//" << endl; // Dequeue 2 elements from queue
HumanQueue.dequeue();
HumanQueue.dequeue();
HumanQueue.PrintQueue();
system("pause");
return 0;
}
“人类”类可以用我选择的任何变量和函数进行解释,所以我没有将它包含在这个线程中。
构造函数、入队和打印工作正常,但在尝试出队时,我得到的返回值为 3221225477。根据我收集到的信息,这意味着程序使用内存的方式存在某种问题。我在以前的项目中使用了相同的模板,其中类型为 int、char、float 并且工作正常,但它不喜欢使用对象。
解决方案
您的dequeue
函数不返回值。
它应该是这样的:
template<class T>
T Queue<T>::dequeue(){
if (index == 0) {
throw std::logic_error("queue is empty");
}
T value = array[0];
for(int i = 0; i < size - 1; i++){
array[i] = array[i + 1];
}
index--;
return value;
}
该异常只是在调用时处理空队列的一个示例dequeue
。
推荐阅读
- json - 如何对推特数据进行分页以显示 100 条或更多最新推文?
- node.js - nodejs获取promise对象值
- gitlab - Gitlab CI/CD 连接到私有服务器
- c# - 即使 IsBodyHtml 属性为 true,电子邮件也不会显示为 HTML
- javascript - 如何生成随机长度的字符串
- r - 如何根据一个值重新排序具有多个变量的图形?
- javascript - 如何创建自定义内置函数的实例?
- c# - 如何在不提取 zip 文件的情况下从内部档案中读取数据?
- api - 如何获得排序/嵌套的 FHIR 捆绑响应?
- docker - 获取“ 60000 毫秒后元数据中不存在主题。”