c ++:打印STL列表
c++: Printing a STL list
我正在浏览 STL 列表,我试图将列表实现为类型 class 而不是 int 或任何其他数据类型。下面是我尝试编译的代码
#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;
}
但它在行中给出了错误:
cout<<' '<<*it;
错误是
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)
^
实际上我想使用代码打印列表的内容above.Can有人帮我解决这个问题吗??
您尝试将 AAA
类型的对象输出到 std::ostream
。为此,您需要为 operator<<
编写重载。像这样:
std::ostream& operator<< (std::ostream& stream, const AAA& lhs)
{
stream << lhs.x << ',' << lhs.y;
return stream;
}
我正在浏览 STL 列表,我试图将列表实现为类型 class 而不是 int 或任何其他数据类型。下面是我尝试编译的代码
#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;
}
但它在行中给出了错误:
cout<<' '<<*it;
错误是
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)
^
实际上我想使用代码打印列表的内容above.Can有人帮我解决这个问题吗??
您尝试将 AAA
类型的对象输出到 std::ostream
。为此,您需要为 operator<<
编写重载。像这样:
std::ostream& operator<< (std::ostream& stream, const AAA& lhs)
{
stream << lhs.x << ',' << lhs.y;
return stream;
}