我的输出流运算符出现编译错误,我似乎无法找到解决方法,因为我以前从未收到过此错误:
linkedList.cpp:258: error: ‘std::ostream& linkedList<T>::operator<<(std::ostream&, linkedList<T>)’ must take exactly one argument
make: *** [linkedList.o] Error 1
这是我的 operator<<
的定义
template <class T>
ostream& linkedList<T>::operator<<(ostream &output, linkedList<T> list)
{
node *curr;
curr=list.head;
while(curr!=NULL )
{
output << curr->data;
curr = curr->next;
}
return output;
}
这是在我的标题中:
//ostream operator for printing the list
template <class T>
ostream &operator<<(ostream &output, linkedList<T> list);
任何帮助将不胜感激!
最佳答案
你将它定义为一个成员函数,你必须将它定义为一个独立的(可能是友元)函数,要么
在类之外
template <class U> ostream& operator<<(ostream &output, linkedList<U> list){...}
在这种情况下,您还必须在类中将其声明为
template <class U> // note the different type name
friend ostream& operator<<(ostream &output, linkedList<U> list)
或
类内部
// no need for template, type is passed automatically the function is not templated anymore friend ostream& operator<<(ostream &output, linkedList list){...}
这 2 个声明之间的区别有点微妙,但对于您的目的而言,两者都同样有效。也许你想通过 linkedList
通过 const
引用,linkedList<T>& list
.
编辑
一个常见的错误是在类中将友元运算符声明为
template<typename T>
class linkedlist
{
//....
friend ostream& operator<<(ostream& output, const linkList& list); // declaration only
}
然后尝试在类外定义为
template<typename T>
ostream& operator<<(ostream& output, const linkList<T>& list){...}
你猜怎么着?代码将编译,但不会链接,因为类中的声明声明了一个非模板 函数,每种类型一个 T
你传递给linkList<T>
.然后,当您声明例如linkList<int> lst
, 然后尝试 cout << lst
,编译器将看到 friend 的声明,它看起来像
friend ostream& operator<<(ostream& output, const linkList<int>& list);
并将尝试搜索它的定义。但是, header 的其余部分没有定义,只有模板运算符,因此链接器无法找到实现并会吐出链接器错误。实例here .
关于c++ - ostream 必须只接受一个参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29859394/