如何在c++中获得存储在列表中的类对象
How to get class objects stored in a list in C++?
我已经定义了自己的类,并将它们的对象存储在std:list中。现在我想挑选所有的元素,但有些地方出错了-我希望这不是太复杂的阅读:
std::map < long, FirstClass*> FirstClassMap;
std::map < long, FirstClass* >::iterator it;
it=this->FirstClassMap.begin()
//initialization of FirstClassMap is somewhere else and shouldn't matter.
list<SecondClass*>::iterator ListItem;
list<SecondClass*> depList = it->second->getSecondClassList();
for(ListItem = depList.begin(); ListItem != depList.end(); ++ListItem)
{
/* -- the error is in this Line -- */
FirstClass* theObject = ListItem->getTheListObject();
std::cout << theObject->Name();
}
还有一个函数:
SecondClass::getTheListObject()
{
return this->theObject; //returns a FirstClass object
}
FirstClass::Name()
{
return this->name //returns a string
}
这里我得到了Error
方法'getTheListObject'无法解析
和
我很抱歉,我不能给你正确的错误信息。我得把它从德语翻译成英语,我看不懂英语) 我看不出有什么问题。有人知道吗?错误:元素请求»getTheListObject«in»*ListItem.std: _List_iterator<_Tp>::操作符->()«,的指针类型是»SecondClass*«(可能是指»->«)
亲切的问候
在您的代码中,ListItem
不是SecondClass*
的实例,它是SecondClass*
的迭代器的实例。必须对迭代器解引用才能访问底层对象。所以你的for循环应该是这样的:
for(ListItem = depList.begin(); ListItem != depList.end(); ++ListItem)
{
FirstClass* theObject = (*ListItem)->getTheListObject(); //Dereference the iterator,
//then call the method.
std::cout << theObject->Name();
}
相关文章:
- C++ 创建包含链表和字符串的对象的链接列表时出错
- 我使用向量来创建类对象列表.初始化向量时如何使用参数调用构造函数?
- 从封装在对象中的函数 C++ 返回时为空的列表
- 如何在不销毁对象的情况下返回对象列表
- 如何使用Q_PROPERTY公开自定义对象列表
- 链接列表在 cpp 中包含不同的对象类
- 如何使用对象制作分数列表并获得平均值
- 什么更好?返回对象指针列表?或返回指向对象列表的指针?
- 如何将成员函数作为参数传递并在派生对象上执行方法列表
- 我可以从列表中获取对象并复制它们,但如何删除我复制的对象?
- 如何获取列表的每个对象并调用getName方法来打印其名称
- 如何在Windows Media Foundation SDK中指定语言列表对象
- 在 DLL 中嵌入 Python:Py_DECREF列表对象时访问冲突读取位置
- 将类的每个实例添加到列表对象的构造函数
- 列表<对象*>迭代器中的分段错误
- 如何使用list::sort()对STL列表对象进行排序,同时将自定义排序函数作为参数传递给list::排序
- 如何防止客户端修改列表对象
- c++列表对象错误
- 在列表对象中使用对象的派生函数
- 编译器错误 使用列表<对象*的迭代器> C++