карта памяти печати ostream, затем выгрузка ядра

У меня есть программа, в которой я пытаюсь реализовать приоритетную очередь. В файле PriorityQueue.h я перегружен оператор ostream <<, но когда эта функция вызывается, после вывода правильных значений из моей очереди, она печатает карту памяти, и затем мое ядро ​​сбрасывается, и программа завершает работу.

Вот вызов для вывода содержимого моей очереди (эта строка находится в моем файле main.cpp);

cout << "Printing Q1" << endl;
cout << Q1 << endl;

где Q1 — моя приоритетная очередь, содержащая значения 10, 5 и 1 в указанном порядке.

вот мой файл PriorityQueue.h, внизу я определил мой перегруженный оператор ostream.

#include "ListT.h"#include <ostream>
using namespace std;

//template <typename T>
template <typename T>
class PriorityQueue : private List<T>
{

public:

//constructor
PriorityQueue();
//add item to priority queue
void enqueue(T item);
//remove the item with the highest priority from the list
void dequeue();
//remove the item with the highest priority and assign its value to T& item
void dequeue(T& item);
//look at the item with highest priority and assign its value to T& item
void peek(T& item) const;
//return the size of the priority queue
int getSize() const;

//overloaded assignment operartor, performs deep copy of rhs
PriorityQueue<T>& operator =(PriorityQueue<T>& rhs);
};//overloaded output operator
template <typename T>
ostream& operator <<(ostream& os, const PriorityQueue<T>& rhs)
{
T item;
PriorityQueue<T> rhsCopy = rhs;
while(rhsCopy.getSize() > 0){
rhsCopy.dequeue(item);
os << item << endl;
}

return os;
}

//overloaded assignment operator/copy constructor
template <typename T>
PriorityQueue<T>& PriorityQueue<T>::operator =(PriorityQueue<T>& rhs)
{
int index = 1, size = rhs.getSize();
T itemCopy;
while(index < size){
rhs->retrieve(index,itemCopy);
*this->enqueue(itemCopy);
index++;
}
return *this;
}

#include "PriorityQueue.cpp"

Редактировать:

Вот вывод программы

********* TEST 1 ***********************************************
Printing Q1
10
5
1

*** glibc detected *** ./lab8: double free or corruption (fasttop): 0x000000000132a030 ***
======= Backtrace: =========
/lib64/libc.so.6[0x397c27bfee]
./lab8[0x4020b7]
./lab8[0x401929]
./lab8[0x402447]
./lab8[0x4014e8]
./lab8[0x401430]
/lib64/libc.so.6(__libc_start_main+0xf5)[0x397c221735]
./lab8[0x401339]
======= Memory map: ========
00400000-00404000 r-xp 00000000 08:01 19792231
/mnt/sda1    /c++/school/lab8/lab8/lab8
00603000-00604000 rw-p 00003000 08:01 19792231
/mnt/sda1    /c++/school/lab8/lab8/lab8
0132a000-0134b000 rw-p 00000000 00:00 0
[heap]
397be00000-397be20000 r-xp 00000000 fd:01 165912
/usr/lib64    /ld-2.15.so
397c01f000-397c020000 r--p 0001f000 fd:01 165912
/usr/lib64/ld-2.15.so
397c020000-397c021000 rw-p 00020000 fd:01 165912
/usr/lib64/ld-2.15.so
397c021000-397c022000 rw-p 00000000 00:00 0
397c200000-397c3ac000 r-xp 00000000 fd:01 165944
/usr/lib64/libc-2.15.so
397c3ac000-397c5ac000 ---p 001ac000 fd:01 165944
/usr/lib64/libc-2.15.so
397c5ac000-397c5b0000 r--p 001ac000 fd:01 165944
/usr/lib64/libc-2.15.so
397c5b0000-397c5b2000 rw-p 001b0000 fd:01 165944
/usr/lib64/libc-2.15.so
397c5b2000-397c5b7000 rw-p 00000000 00:00 0
397d200000-397d2fa000 r-xp 00000000 fd:01 165973                         /usr/lib64/libm-2.15.so
397d2fa000-397d4f9000 ---p 000fa000 fd:01 165973                         /usr/lib64/libm-2.15.so
397d4f9000-397d4fa000 r--p 000f9000 fd:01 165973                         /usr/lib64/libm-2.15.so
397d4fa000-397d4fb000 rw-p 000fa000 fd:01 165973                         /usr/lib64/libm-2.15.so
3980a00000-3980a15000 r-xp 00000000 fd:01 165976                         /usr/lib64/libgcc_s-4.7.2-20120921.so.1
3980a15000-3980c14000 ---p 00015000 fd:01 165976                         /usr/lib64/libgcc_s-4.7.2-20120921.so.1
3980c14000-3980c15000 rw-p 00014000 fd:01 165976                         /usr/lib64/libgcc_s-4.7.2-20120921.so.1
3988a00000-3988ae5000 r-xp 00000000 fd:01 155500                         /usr/lib64/libstdc++.so.6.0.17
3988ae5000-3988ce4000 ---p 000e5000 fd:01 155500                         /usr/lib64/libstdc++.so.6.0.17
3988ce4000-3988cec000 r--p 000e4000 fd:01 155500                         /usr/lib64/libstdc++.so.6.0.17
3988cec000-3988cee000 rw-p 000ec000 fd:01 155500                         /usr/lib64/libstdc++.so.6.0.17
3988cee000-3988d03000 rw-p 00000000 00:00 0
7fed62cd9000-7fed62cde000 rw-p 00000000 00:00 0
7fed62cf4000-7fed62cf7000 rw-p 00000000 00:00 0
7fff06836000-7fff06857000 rw-p 00000000 00:00 0                          [stack]
7fff06862000-7fff06863000 r-xp 00000000 00:00 0                          [vdso]
ffffffffff600000-ffffffffff601000 r-xp 00000000 00:00 0                  [vsyscall]
Aborted (core dumped)

0

Решение

Самой большой проблемой в вашем коде является тот факт, что вы создали шаблон своего класса PriorityQueue, а затем попытались использовать функцию ostream в другом месте.

template <typename T>
class PriorityQueue : private List<T>
{
...
}

Это хорошая реализация, но когда вы создаете функцию ostream, она не может соответствовать типу шаблона тому, что есть у класса.

template <typename T>
ostream& operator <<(ostream& os, const PriorityQueue<T>& rhs)
{
...
}

Помните, что шаблоны создаются во время компиляции. Когда вы создаете объект PriorityQueue (скажем, int для аргументов), вы выполняете все реализации PriorityQueue: 🙁 вставьте здесь функцию). Когда вы пытаетесь позвонить Ostream << PriorityQueue никогда не было создано функции для обработки этого, потому что во время компиляции не было никаких причин для вызова ostream operator<<(ostream&, PriorityQueue<T>),

Чтобы это исправить, все, что вам нужно сделать, это сделать функцию ostream внутри определения класса.

template <typename T>
class PriorityQueue : private List<T>
{
...
friend ostream& operator <<(ostream& os, const PriorityQueue<T>& rhs)
{
...
}
}

Теперь каждый раз, когда вы создаете объект PriorityQueue, он будет иметь свою собственную функцию ostream. Так что PriorityQueue<int> будет иметь ostream& operator <<(ostream&, const PriorityQueue<int>&) функция и PriorityQueue<std::string> будет иметь ostream& operator <<(ostream&, const PriorityQueue<std::string>&) функция.

0

Другие решения

Других решений пока нет …

По вопросам рекламы ammmcru@yandex.ru
Adblock
detector