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

标签 c++ templates linked-list linker-errors friend

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

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

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

最佳答案

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

如果你这样声明 friend

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

然后 operator << <int>将成为LinkedList<float>的 friend .如果这是不可取的,有这个解决方案:

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

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

This article详细解释主题

关于c++ - 在模板链表中使用友元函数时出现链接错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8545495/

相关文章:

c++ - 在 C++ 中调用 ASM 函数

C++ 17类模板参数类型推导——可读性

java - 这个删除重复链表的 void 函数是如何完成任务的呢? Java中的参数传递

C - 合并两个链接列表

c++ - 未声明的标识符自定义类

c++ - 在 C++ 应用程序的 CFB 模式下,AES.h 中的 AES-256 加密应该使用哪个函数?

c++ - 复制构造动态分配对象的问题

c++ - 在 C++ 中为 BST 类(不同类型的键)制作模板

c++ - 模板的总类特化

c - 如何对链表指针进行排序