在模板链接列表中使用友元函数时出现链接错误

Link error when using friend function in template linkedlist

本文关键字:链接 函数 友元 错误 列表      更新时间:2023-10-16

我编写了一个模板链表(在.h文件中(,但出现链接错误。

template <typename T>
class LinkedList
{
private:
    Node<T>* head;
    Node<T>* tail;
    int size;
public:
    LinkedList();
    ~LinkedList();
    inline T* Front() {return &(this->head);};
    inline const T* Front() const {return (const T*)this->head;};
    void InsertFirst(const T&);
    void InsertLast(const T&);
    void RemoveFirst();
    void RemoveLast ();
    void RemoveItem (const T&);
    void Sort();
    void Clear();
    inline bool Exists(const T&) const;
    bool Empty() const {return this->size==0 ? true : false;};
    inline int Size() const {return this->size;};
    T* At(const int index);
    const T* At(int index) const; 
    friend ostream& operator << (ostream& out, const LinkedList<T>& that);
    T* operator[](const int);
    const T* operator[](const int) const;   
};
.
.
.
template <typename T>
ostream& operator << (ostream& out, const LinkedList<T>& that)
{
    if (!that.Empty())
        for(Node<T>* seeker=that.head; seeker; seeker=seeker->next)
            out<<seeker->info<<endl;
    return out;
}

由于某种原因,当我在类中编写 friend 函数的声明时,链接错误消失了:

template <typename T> friend ostream& operator << (ostream& out, const LinkedList<T>& that);
事情

是这样的:你声明的朋友不是模板,所以你的<<模板的给定实例不是你声明的朋友。

如果你这样声明朋友

template <typename U> //or T, doesn't matter
friend ostream& operator << (ostream& out, const LinkedList<U>& that);

那么operator << <int>将成为LinkedList<float>的朋友.如果这是不可取的,有以下解决方案:

friend ostream& operator <<<T> (ostream& out, const LinkedList<T>& that);

在这种情况下,只有模板的特定实例化才是您的朋友,这可能是您需要的。

本文详细解释了该主题

因为类外operator<<的定义其实是一个函数模板,而类内部的友元声明不是函数模板。

friend声明是一个非模板函数,其参数相对于类模板是固定的。

例如,如果使用 int 实例化类模板,则friend变为:

friend ostream& operator << (ostream& out, const LinkedList<int>& that);

它告诉编译器"我是这个类的朋友,我也是一个非模板函数,你会在类之外找到我的定义,完全相同的签名。您可以看到参数是固定的。

但是当你做这样的事情时:

template <typename U>
friend ostream& operator << (ostream& out, const LinkedList<U>& that);

这对编译器有意义,因为它与类外operator<<的定义一致,这也是一个函数模板。但是有一个问题:它使函数模板的每个专用化都成为类的朋友;表示当U=float时,operator<<也可以访问LinkedList<int>的私有成员,而它应该只能访问LinkedList<float>的私有成员。 所以你看,这就是问题所在。

更好的解决方案是:不要让它成为函数模板,并在类本身中定义友元。

template<typename T>
class LinkedList
{
  public:

  friend ostream& operator << (ostream& out, const LinkedList<T>& that)
  {
      //definition 
  }
};