"error: base operand of ‘->’ has non-pointer type ‘***’" error when calling a method from another class with iterator

"error: base operand of ‘->’ has non-pointer type ‘***’" error when calling a method from another class with iterator

我正在实施一种方法,该方法在关联数组中按名称搜索 Object 类型的 object。然后使用 class Object 中定义的方法 display 显示其元素。方法是这样实现的:

//Method SearchObject in class Gestion
#include "object.h"
void Gestion::SearchObject(string nameobj) const{

    stringstream ss;

    auto it = objectname.find(nameobj);
    if (it == objectname.end())
        cout << "Not found!" << endl;
    else
           (*it)->display(ss); //Error reported in this line
           cout << ss.str() << endl;
}

然而,编译时出现以下错误:

error: base operand of ‘->’ has non-pointer type ‘const std::pair<const std::basic_string<char>, std::shared_ptr<Object> >’
            (*it)->display(ss);

方法 display 在 class Object 中声明,我已经通过从其他 classes 调用它进行了测试。在 class 的 header Gestion 中,变量是这样声明的:

//File gestion.h
typedef std::shared_ptr<Object> ObjPtr;
typedef map<string, ObjPtr> Objectmap;

class Gestion { 
private:
         Objectmap objectname;
public:
    Gestion(Objectmap objectname);
    virtual ~Gestion() {}

    virtual void SearchObject(string nameobj) const; 
};

如何在我正在实施的新方法中使用方法 display

看起来 Objmultomedia 是 std::pair。您需要从对的第二个元素调用 display

it->second->display(ss);

迭代器以指针为模型,因此您可以对它们使用取消引用运算符 *,或对它们使用指向结构的指针访问运算符 ->

但是,指向结构的指针访问运算符 -> 已经在进行取消引用,因此您不能将两者结合使用。

it->display(ss) (*it).display(ss).


那是个谎言,因为迭代器是 "pointing" 到 std::pair,其 second 成员是一个指针,所以 您应该使用 *-> 取消引用,例如 it->second->display(ss)(*it).second->display(ss),或 (*it->second).display(ss)(*(*it).second).display(ss).