c++:打印STL列表
c++: Printing a STL list
我正在浏览STL列表,并试图将列表实现为类型类,而不是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)
^
实际上,我想使用上面的代码打印列表的内容。有人能帮我解决这个问题吗??
您尝试将类型为AAA
的对象输出到std::ostream
。为此,您需要为operator<<
编写一个重载。类似这样的东西:
std::ostream& operator<< (std::ostream& stream, const AAA& lhs)
{
stream << lhs.x << ',' << lhs.y;
return stream;
}
相关文章:
- 在STL - C++中按成绩对学生列表进行排序?
- 使用列表 STL 递归进行插入排序
- 如何在 c++ stl 中获取列表中被推回的元素的地址,在常量时间内?
- 如何检查C ++ STL列表是否为回文?
- 打印/修改类对象的特定成员变量,其类定义列表 (STL) 包含的元素类型
- C++ 在列表末尾插入元素的列表的 STL 向量
- 清除 C++ 中的指针的 STL 列表
- 在列表中找到最常见的元素(C STL)
- 在Visual Studio 2013中编译的STL列表代码在Visual Studio 2019中给出了错误.想知道原
- 列表STL的时间复杂性在一段时间内进行排序
- 使用.txt文件填充 STL 列表不起作用
- 在 stl 映射和列表 (c++) 上进行迭代的泛型循环
- 为 STL 列表编写选择排序
- STL C 中不同类型的列表声明的错误
- 使用队列和列表 STL 进行C++分配。在将数据填充到列表或队列中然后打印该数据时遇到问题
- 如何从 STL 列表中删除结构记录
- C++如何将 STL 列表传递给函数
- 漂亮的打印不适用于C ++ STL列表
- 使用列表 STL 时出错
- 如何将列表 STL 的迭代器转换为实例 (C++)