gpt4 book ai didi

c++ - C++程序使用类模板模拟FIFO,出队时返回值3221225477

转载 作者:行者123 更新时间:2023-12-02 10:03:14 25 4
gpt4 key购买 nike

我目前正在大学里学习第二门C++面向对象编程类(class),因此我的代码可能会遇到不好的编程习惯和普遍错误,因此,请指出是否有错误。我总是开放学习。

我目前在C++模板上有一项作业,我必须使用一个类来创建程序,该类使用不同的类作为模板类型(Queue HumanQueue)来模拟FIFO(先进先出)队列。

Queue.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

Queue.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();
}
}

main.cpp
#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;
}

“Human”类可以选择任何变量和函数进行解释,因此不包含在该线程中。

构造函数,入队和打印工作正常,但是当尝试出队时,我得到的返回值为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;
}

异常(exception)只是在调用 dequeue时处理空队列的示例。

关于c++ - C++程序使用类模板模拟FIFO,出队时返回值3221225477,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61500835/

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