【问题标题】:How to get class objects stored in a list in C++?如何获取存储在 C++ 列表中的类对象?
【发布时间】:2014-08-18 04:51:33
【问题描述】:

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

这里出现错误

方法“getTheListObject”无法解析

错误:元素请求 »getTheListObject« in »* ListItem.std::_List_iterator<_tp>::operator->()«,其 指针类型是 »SecondClass*«(可能是 »->« 的意思)

(对不起,我不能给你正确的错误信息。我必须把它从德语翻译成英语,我没有得到这些英文)

我真的没有看到问题所在。有人有想法吗?

亲切的问候

【问题讨论】:

标签: c++ list pointers map iterator


【解决方案1】:

在您的代码中,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();
}

【讨论】:

    猜你喜欢
    • 2019-10-17
    • 1970-01-01
    • 1970-01-01
    • 2013-04-02
    • 2020-03-12
    • 1970-01-01
    • 1970-01-01
    • 2020-09-02
    • 1970-01-01
    相关资源
    最近更新 更多