如何使用迭代器在列表中打印类对象
How to use an iterator to print class objects in a list
我目前有一个创建对象的程序。我可以看到这个对象是用我的描述方法成功创建的。我通过这样做将这个对象放入一个列表:
list<GameObject*> roomObjects5;
auto * obj1 = new GameObject(&o1name,&o1desc,&o1key);
roomObjects5.push_back(obj1);
我现在正试图使用迭代器打印这个名为roomObjects 5的列表
void print(const list<GameObject>& s) {
list<GameObject>::iterator i;
for( i = s.front(); i != s.end(); ++i)
cout << *i << " ";
cout << endl;
}
但是出现错误
类"const gameObject"与不兼容class'list::迭代器
和
二进制运算符'<lt;'不能应用于表达式"ostream"answers"游戏对象">
并且当我运行时,我得到错误:
错误:在"{"标记之前,此处不允许函数定义无效打印(常量列表&s){^
mingw32 make.exe[3]:*[CMakeFiles/textadv.dir/main.cpp.obj]错误1CMakeFiles\textadv.dir\build.make:61:目标配方"CMakeFiles/textadv.dir/main.cpp.obj"失败mingw32 make.exe[2]:[CMakeFiles/textdv.dir/all]错误2 CMakeFiles\Makefile2:66:配方对于目标"CMakeFiles/textadv.dir/all",mingw32 make.exe[1]失败:[CMakeFiles/textadv.dir/rule]错误2 CMakeFiles\Makefile2:78:目标"CMakeFiles/textadv.der/rule"的配方失败mingw32-make.exe:*[textadv]错误2生成文件:117:的配方目标"textadv"失败
有人能帮我吗?
更新:
> void print(const list<GameObject>& s) {
> list<GameObject *>::iterator i;
> for (i = s.front(); i != s.end(); ++i)
> cout << *(*i) << " ";
>
> cout << endl; }
我现在正在尝试这个,我得到错误
类"const GameObject"与类不兼容"list::迭代器">
更新2:
我现在正在尝试这个:
无效打印(常量列表&s){列表:迭代器i;
for(auto i = s.front(); i != s.end(); ++i)
cout << *(*i) << " ";
cout << endl;
}
以及的错误
i != s.end
线路
"蚂蚁比较结构">
和
++i
GameObject类型的表达式既不是数字也不是指针
和
*(*i)
"需要指针类型">
根据list::front()
:上的文档
返回对列表容器中第一个元素的引用。
与向同一元素返回迭代器的成员list::begin不同,此函数返回一个直接引用。
在空容器上调用此函数会导致未定义的行为。
不要使用front()
,而是使用返回迭代器的begin()
。此外您正在通过const list<GameObject>&
,而您的原始列表是list<GameObject*>
。您的函数无法接受您的列表。代码看起来像:
void print(const list<GameObject*>& s) {
for (auto i = s.begin(); i != s.end(); ++i)
cout << *(*i) << " ";
cout << endl;
}
更新:似乎您没有重载ostream& operator << (ostream& out, GameObject& gObj)
。你应该定义它:
ostream& operator << (ostream& out, GameObject& gObj){
out << gObj.(whatever you want to print out from GameObject);
return out;
}
更新2:
我制作了一个用于测试的伪代码,它运行正常:
#include <iostream>
#include <list>
using namespace std;
class Noob {
public:
int bad_data;
};
ostream& operator << (ostream& s, Noob& noob) {
s << noob.bad_data;
return s;
}
void print(const list<Noob*> list) {
for (auto i = list.begin(); i != list.end(); ++i)
cout << *(*i) << " ";
}
int main() {
list<Noob*> list;
for (int i = 0; i < 10; i++)
list.push_back(new Noob());
print(list);
return 0;
}
输出:
0 0 0 0 0 0 0 0 0 0
- 将对象放入地图后打印对象
- 打印对象的映射,其中另一个对象作为键
- 如何在C++中打印对象向量的内容
- C++ - 使用 std::list,如何打印对象的私有成员的链接列表?
- 使用成员函数打印对象
- 如何在C++中转换可打印对象中的对象
- 打印对象矢量的意外输出
- 如何使用 is_invocable() 创建用于重载<<打印对象的模板?
- 运算符重载<<,打印对象矢量时遇到问题
- 我正在尝试循环浏览对象的向量并打印对象的每个元素
- 在更改对象值后,打印对象数组仍会给出相同的值
- 声明并使用静态列表来打印对象(在c++中)
- 为什么写入临时字符串流对象只打印对象地址
- 打印对象数组
- 有没有一种方法可以打印对象的位表示
- OpenCV - 仅在绘制单应性时打印对象名称
- 在矢量 C++ 中可视化打印对象中的对象
- 使用 cout 打印对象指针值时地址长度不同
- C++模板打印对象名称
- 使用 c++ 中的重载运算符<<打印对象的动态数组