简体   繁体   English

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

[英]Undefined reference to friend function in template class

The following codes are in file Heap.h以下代码在文件 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.在 testheap.cpp 文件中,我使用了这个模板类,当我编译时,发生了对 << 运算符重载函数错误的未定义引用。 Confused with this situation.对这种情况感到困惑。 When I put the definition of the function in the class, it works.当我将函数的定义放在类中时,它就起作用了。 The OS is Ubuntu, compiler is g++.操作系统是Ubuntu,编译器是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)
{
     ...
}

Try this :尝试这个 :

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

I had the same problem.我有同样的问题。 Here is the question这是问题

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM