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.
这篇文章详细解释了这个话题
这篇关于在模板链表中使用友元函数时出现链接错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:在模板链表中使用友元函数时出现链接错误


基础教程推荐
- 为 C/C++ 中的项目的 makefile 生成依赖项 2022-01-01
- 如何使图像调整大小以在 Qt 中缩放? 2021-01-01
- 在 C++ 中循环遍历所有 Lua 全局变量 2021-01-01
- 管理共享内存应该分配多少内存?(助推) 2022-12-07
- Windows Media Foundation 录制音频 2021-01-01
- 为什么语句不能出现在命名空间范围内? 2021-01-01
- 使用从字符串中提取的参数调用函数 2022-01-01
- 如何“在 Finder 中显示"或“在资源管理器中显 2021-01-01
- 如何在不破坏 vtbl 的情况下做相当于 memset(this, ...) 的操作? 2022-01-01
- 从 std::cin 读取密码 2021-01-01