首页 > 解决方案 > 使用模板类重载 cout

问题描述

我正在将我的类重建为模板,但我在重载 cout 时遇到了问题(没有模板工作)。当我尝试编译时,gcc 会抛出此错误:

error: ‘LinkedList’ is not a type
ostream& operator <<(ostream&, LinkedList&);

LinkedList.h 类的代码是:

template <typename value_type>

class LinkedList
{
public:
LinkedList();

~LinkedList();

void addToHead(const typename node<value_type>::value_type& entry);
void addToTail(const typename node<value_type>::value_type& entry);
void set_current(node<value_type>* entry);
void remove(string);
void remove_from_head();
void remove_from_tail();
void list_clear();

int list_length();
int count(string name);
double calcAverage();
bool search(string);
node<value_type> * get_head();
node<value_type> * get_tail();
node<value_type> * get_current();

LinkedList& operator+=(LinkedList&);

private:
node<value_type>* head;
node<value_type>* tail;
node<value_type>* current;
};
template <typename value_type>
ostream& operator <<(ostream&, LinkedList&);

我认为这与模板有关,并且这部分代码超出了类的范围,但是 typedef 的不同组合似乎会导致更多错误。

标签: c++

解决方案


确实LinkedList不是那里的类型,它是template.

您可以通过实例化模板来创建模板类型,用类型替换它的模板参数。

template <typename value_type>
ostream& operator <<(ostream&, const LinkedList<value_type>&);

编辑:正如@Scheff 所建议的,列出的链接也应该是const,因为不operator<<应该改变它。


推荐阅读