gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-29 20:29:57 25 4
gpt4 key购买 nike

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

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com