C++ ToString用于模板化链表?
这是我的密码:C++ ToString用于模板化链表?,c++,linked-list,stdout,C++,Linked List,Stdout,这是我的密码: template<typename T> class list { private: node<T>* head; node<T>* tail;
template<typename T>
class list {
private:
node<T>* head;
node<T>* tail;
int len;
public:
list(){
this->len = 0;
this->head = this->tail = 0;
}
~list(){
node<T>* n = this->head;
if (!n) return;
node<T>* t = NULL;
while (n){
t = n->next;
delete n;
n = t;
}
}
/* other stuff */
ostream& operator<<(ostream &o, const list<T>& l) {
node<T>* t = l.head;
while (t){
strm << *(t->value);
if (!t->next) break;
strm << ", ";
t = t->next;
}
return strm;
}
};
模板
类列表{
私人:
节点*头;
节点*尾部;
内伦;
公众:
列表(){
这个->len=0;
此->头部=此->尾部=0;
}
~list(){
节点*n=此->头部;
如果(!n)返回;
node*t=NULL;
而(n){
t=n->next;
删除n;
n=t;
}
}
/*其他东西*/
ostream&operator你能试着让操作符成为你的操作符吗我最终使用了boost::lexical_cast
和建议的ostream&operator请使用降价,而不是HTML。3年半的时间足够学习如何在堆栈溢出时格式化帖子…:)或者干脆把friend
放在前面类中的定义(无需将其移出)。@LokiAstari true,这确实有效,但它滥用了friend
关键字来放置operator@je4d:你从哪里知道这是对朋友的滥用?我一直喜欢把声明作为朋友留在课堂上。
rm bin *.o -f
g++ -g -Wall main.cpp -o bin
main.cpp:110: error: 'std::ostream& list<T>::operator<<(std::ostream&, const list<T>&)' must take exactly one argumentmain.cpp: In function 'int main(int, char**)':
main.cpp:151: error: no match for 'operator<<' in 'std::cout << l'
/usr/include/c++/4.4/ostream:108: note: candidates are: std::basic_ostream<_CharT, _Traits>& std::basic_ostream<_CharT, _Traits>::operator<<(std::basic_ostream<_CharT, _Traits>& (*)(std::basic_ostream<_CharT, _Traits>&)) [with _CharT = char, _Traits = std::char_traits<char>]
... other errors
make: *** [main] Error 1
....;
friend ostream& operator<<(ostream &o, const list<T>& l) {
....;
template <class T>
class list {
// ...
};
template <class T>
ostream& operator<<(ostream &o, const list<T>& l)
{
// ...
};