2
下面的代碼在文件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;
}
在testheap.cpp文件,我用這個模板類,當我編譯,一個未定義的參考< <運算符重載函數發生錯誤。與這種情況相混淆。 當我把這個函數的定義放在類中時,它就起作用了。 操作系統是Ubuntu,編譯器是g ++。
你犯了一個小錯誤,你應該改變「T」到「T2」中的「常量堆和堆」。當跨越引起的錯誤來模板,我總是沒有想法如何解決。你有沒有發現一些好的學習模板? –
haipeng31