Link error when using friend function in template linkedlist(在模板链表中使用友元函数时出现链接错误)
问题描述
我编写了一个模板链表(在 .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.
这篇文章详细解释了这个话题
这篇关于在模板链表中使用友元函数时出现链接错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:在模板链表中使用友元函数时出现链接错误
- 一起使用 MPI 和 OpenCV 时出现分段错误 2022-01-01
- 从python回调到c++的选项 2022-11-16
- 近似搜索的工作原理 2021-01-01
- 与 int by int 相比,为什么执行 float by float 矩阵乘法更快? 2021-01-01
- 静态初始化顺序失败 2022-01-01
- C++ 协变模板 2021-01-01
- 如何对自定义类的向量使用std::find()? 2022-11-07
- STL 中有 dereference_iterator 吗? 2022-01-01
- Stroustrup 的 Simple_window.h 2022-01-01
- 使用/clr 时出现 LNK2022 错误 2022-01-01