[英]c++: Printing a STL list
I was going through STL list and I tried to implement the list as type class instead of int or any other data type.我正在浏览 STL 列表,并尝试将列表实现为类型类,而不是 int 或任何其他数据类型。 Below is the code I tried to compile
下面是我试图编译的代码
#include <iostream>
#include <list>
using namespace std;
class AAA {
public:
int x;
float y;
AAA();
};
AAA::AAA() {
x = 0;
y = 0;
}
int main() {
list<AAA> L;
list<AAA>::iterator it;
AAA obj;
obj.x=2;
obj.y=3.4;
L.push_back(obj);
for (it = L.begin(); it != L.end(); ++it) {
cout << ' ' << *it;
}
cout << endl;
}
But it is giving error in the line:但它在行中给出错误:
cout<<' '<<*it;
and the error is错误是
In function 'int main()':
34:13: error: cannot bind 'std::basic_ostream<char>' lvalue to 'std::basic_ostream<char>&&'
In file included from /usr/include/c++/4.9/iostream:39:0,
from 1:
/usr/include/c++/4.9/ostream:602:5: note: initializing argument 1 of 'std::basic_ostream<_CharT, _Traits>& std::operator<<(std::basic_ostream<_CharT, _Traits>&&, const _Tp&) [with _CharT = char; _Traits = std::char_traits<char>; _Tp = AAA]'
operator<<(basic_ostream<_CharT, _Traits>&& __os, const _Tp& __x)
^
Actually I want to print the contents of the list using the code above.Can somebody help me in solving this??其实我想使用上面的代码打印列表的内容。有人可以帮我解决这个问题吗??
You try to output an object of type AAA
to a std::ostream
.您尝试将
AAA
类型的对象输出到std::ostream
。 To do that, you need to write an overload for operator<<
.为此,您需要为
operator<<
编写一个重载。 Something like this:像这样的东西:
std::ostream& operator<< (std::ostream& stream, const AAA& lhs)
{
stream << lhs.x << ',' << lhs.y;
return stream;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.