ostream<<迭代器,C++
我正在尝试构建一个打印列表的运算符,
为什么 ostream<<* 无法编译?
void operator<<(ostream& os, list<class T> &lst)
{
list<T>::iterator it;
for(it = lst.begin(); it!=lst.end(); it++)
{
os<<*it<<endl; //This row
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
因为
*it
没有实现流插入。也就是说,采用ostream
和T
的operator<<
没有重载。请注意,您应该返回 ostream& os 以允许运算符链接。此外,您的函数模板定义看起来也是错误的。考虑这样做:或者更好的是,支持所有类型的元素和特征上的流:
此外,您可以将分隔符传递给 std::ostream_iterator 构造函数以在每个元素之间插入。
* 更新:*
我只是注意到,即使您的函数模板声明是正确的,您也会处理依赖类型。迭代器依赖于类型
T
,因此您需要将此告知编译器:Because
*it
does not implement stream insertion. That is, there is no overload foroperator<<
that takes anostream
and aT
. Note that you should be returning theostream& os
to allow operator chaining. Also your function template definition looks wrong. Consider doing this instead:or better yet, to support streams over all kind of elements and traits:
Adittionaly, you can pass a separator to
std::ostream_iterator
constructor to be inserted between each element.* Update: *
I just noticed that even if your function template declaration were correct, you would be dealing with a dependent type. The iterator is dependent on the type
T
, so you need to tell this to the compiler:我认为问题出在你的模板声明中。以下内容应该可以编译并正常工作:
当然,前提是列表的元素类型实际上可以与
ostream
的<<
运算符一起使用。I think the problem is in your template declaration. The following should compile and work just fine:
This is provided of course that the element type of your list can actually be used with the
<<
operator of anostream
.您使用模板语法的方式是错误的:
顺便说一句,您应该返回对流的引用以允许链接输出运算符,并且列表应该是 const,并且您还可以使用标准库来执行输出循环:
You are using template syntax the wrong way:
And by the way, you should return a reference to the stream to allow chaining of output operators, and the list should be const, and you can also use the standard library for doing the output loop:
重写为:
Rewrite to: