2012-12-01 70 views
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 ++。

回答

0

試試這個:

template <typename T2> 
friend ostream &operator<< (ostream &os, const Heap<T2> &heap); 

我有同樣的問題。這裏是question

+0

你犯了一個小錯誤,你應該改變「T」到「T2」中的「常量堆和堆」。當跨越引起的錯誤來模板,我總是沒有想法如何解決。你有沒有發現一些好的學習模板? – haipeng31

2

下面應該工作:

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) 
{ 
    ... 
}