在模板链接列表中使用友元函数时出现链接错误
Link error when using friend function in template linkedlist
我编写了一个模板链表(在.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;
}
由于某种原因,当我在类中编写 friend 函数的声明时,链接错误消失了:
template <typename T> friend ostream& operator << (ostream& out, const LinkedList<T>& that);
事情
是这样的:你声明的朋友不是模板,所以你的<<模板的给定实例不是你声明的朋友。
如果你这样声明朋友
template <typename U> //or T, doesn't matter
friend ostream& operator << (ostream& out, const LinkedList<U>& that);
那么operator << <int>
将成为LinkedList<float>
的朋友.如果这是不可取的,有以下解决方案:
friend ostream& operator <<<T> (ostream& out, const LinkedList<T>& that);
在这种情况下,只有模板的特定实例化才是您的朋友,这可能是您需要的。
本文详细解释了该主题
因为类外operator<<
的定义其实是一个函数模板,而类内部的友元声明不是函数模板。
friend
声明是一个非模板函数,其参数相对于类模板是固定的。
例如,如果使用 int
实例化类模板,则friend
变为:
friend ostream& operator << (ostream& out, const LinkedList<int>& that);
它告诉编译器"我是这个类的朋友,我也是一个非模板函数,你会在类之外找到我的定义,完全相同的签名。您可以看到参数是固定的。
但是当你做这样的事情时:
template <typename U>
friend ostream& operator << (ostream& out, const LinkedList<U>& that);
这对编译器有意义,因为它与类外operator<<
的定义一致,这也是一个函数模板。但是有一个问题:它使函数模板的每个专用化都成为类的朋友;表示当U=float
时,operator<<
也可以访问LinkedList<int>
的私有成员,而它应该只能访问LinkedList<float>
的私有成员。 所以你看,这就是问题所在。
更好的解决方案是:不要让它成为函数模板,并在类本身中定义友元。
template<typename T>
class LinkedList
{
public:
friend ostream& operator << (ostream& out, const LinkedList<T>& that)
{
//definition
}
};
相关文章:
- 内联函数中具有内部链接的全局变量
- 使用C链接在函数内部创建C++模板
- 返回一个带有 std::move 的对象并链接函数
- 无法使函数公开。获取:"LNK2005"错误。如何调试链接器错误
- 链接器错误:无法解析构造函数
- C++线程找不到函数作为参数(链接器)
- 使用动态链接加载程序 <dlfcn.h> 而不是直接函数调用的目的是什么?
- 构造函数的链接时间自动注册
- Doxygen:不为非成员函数生成超链接
- 静态库中的 g++ 错误链接函数
- 编写链接函数的更短/更有效的方法,该函数按字典顺序添加新元素
- 仅当链接函数 C++ 时,才会发生"Expression must have class type error"
- 反向动态链接函数调用
- OpenGL GLX_EXT_swap_control存在,但无法链接函数
- C++哈希链接函数
- c++中对链接函数的未定义引用
- 在运行时用LD_PRELOAD链接函数
- C++标准是否规定C链接函数为“noexcept”
- 可以用不同的名称链接函数
- 共享库没有链接函数