我定义了自己的类并将它们的对象存储在 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
}
这里我得到了错误
Method 'getTheListObject' could not be resolved
和
Error:element request »getTheListObject« in »* ListItem.std::_List_iterator<_Tp>::operator->()«, whose pointer type is »SecondClass*« (maybe »->« was meant)
(对不起,我不能给你正确的错误信息。我必须把它从德文翻译成英文,我没有英文)
我真的看不出问题所在。有人有想法吗?
亲切的问候
最佳答案
在您的代码中,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++ 列表中的类对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24445703/