如何使用迭代器在列表中打印类对象

How to use an iterator to print class objects in a list

本文关键字:打印 对象 列表 何使用 迭代器      更新时间:2023-10-16

我目前有一个创建对象的程序。我可以看到这个对象是用我的描述方法成功创建的。我通过这样做将这个对象放入一个列表:

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