模板类中对友元函数的未定义引用

hai*_*g31 7 c++ templates

以下代码位于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;
    }
Run Code Online (Sandbox Code Playgroud)

在一个testheap.cpp文件中,我使用这个模板类,当我编译时,出现了对<<运算符重载函数的未定义引用错误。对这种情况很困惑。当我将函数的定义放入类中时,它就起作用了。操作系统是Ubuntu,编译器是g++。

NPE*_*NPE 7

以下应该有效:

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)
{
     ...
}
Run Code Online (Sandbox Code Playgroud)


ash*_*shr 0

尝试这个 :

template <typename T2> 
friend ostream &operator<< (ostream &os, const Heap<T2> &heap);
Run Code Online (Sandbox Code Playgroud)

我有同样的问题。这是问题