在模板链表中使用友元函数时出现链接错误 [英] Link error when using friend function in template linkedlist

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

问题描述

我编写了一个模板链表(在 .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);

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

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.

这篇文章详细解释了这个话题

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

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆