如何在c++中获得存储在列表中的类对象

How to get class objects stored in a list in C++?

本文关键字:列表 对象 存储 c++      更新时间:2023-10-16

我已经定义了自己的类,并将它们的对象存储在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();
}