В настоящее время я изучаю свой второй курс объектно-ориентированного программирования на C ++ в университете, поэтому, вероятно, у меня будут плохие методы программирования и общие ошибки в моем коде, поэтому, пожалуйста, укажите их, если они появятся. Я всегда открыт для изучения.
В настоящее время у меня есть задание на шаблонах C ++, где я должен создать программу с классом, имитирующим очередь FIFO (первым пришел - первым вышел), используя другой класс в качестве шаблона. тип (Очередь HumanQueue).
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
Очередь. 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;
}
Класс "Человек" открыт для интерпретации с любыми переменными и функциями по моему выбору, поэтому я не включаю его в эту ветку .
Конструктор, постановка в очередь и печать работают нормально, но при попытке удаления из очереди я получаю возвращаемое значение 3221225477. Из того, что я собрал, это означает, что это какая-то проблема с тем, как программа использует Память. Я использовал этот же шаблон для предыдущего проекта, где были типы int, char, float, и он работал нормально, но он не любит работать с объектами.