在模板链表中使用好友功能时出现链接错误

在模板链表中使用好友功能时出现链接错误

本文介绍了在模板链表中使用好友功能时出现链接错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I programmed a template linked list(in .h file) and I get link error.

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;
}

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

For some reason the link error disappears when I write instead in the declaration of the friend function in the class:

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

推荐答案

在这里是这样:您声明的朋友不是模板,因此给定的<<实例.模板不是您声明的朋友.

Here's the thing: the friend you declared is not a template, so the given instantiation of your << template isn't the one you declared friend.

如果您这样宣布朋友

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

然后 operator<<< int> 将是 LinkedList< float> 的朋友.如果不希望这样做,请采取以下解决方案:

then operator << <int> will be a friend of LinkedList<float>. If that is undesirable, there is this solution:

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

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

In this case, only the particular instantiation of the template is your friend, which might be what you need.

本文详细介绍了该主题

这篇关于在模板链表中使用好友功能时出现链接错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-21 18:54