The following codes are in file Heap.h
template <typename T>
class Heap {
public:
Heap();
Heap(vector<T> &vec);
void insert(const T &value);
T extract();
T min();
void update(int index, const T &value);
/* for debug */
friend ostream &operator<< (ostream &os, const Heap<T> &heap);
#if 0
{
for (int i = 0; i < heap.vec_.size(); i++) {
os << heap.vec_[i] << " ";
}
return os;
}
#endif
private:
void minHeapify(int index);
int left(int index);
int right(int index);
int parent(int index);
void swap(int, int);
vector<T> vec_;
};
template <typename T>
ostream &operator<<(ostream &os, const Heap<T> &heap)
{
for (int i = 0; i < heap.vec_.size(); i++) {
os << heap.vec_[i];
}
return os;
}
In a testheap.cpp file, I use this template class, when I compile, an undefined reference to the << operator overloading function error occur. Confused with this situation. When I put the definition of the function in the class, it works. The OS is Ubuntu, compiler is g++.
The following should work:
template <typename T>
class Heap {
public:
...
template<class U>
friend ostream &operator<<(ostream &os, const Heap<U> &heap);
...
};
template <typename T>
ostream &operator<<(ostream &os, const Heap<T> &heap)
{
...
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With