C ++成员参考基本类型'Vertex * const'不是结构或联合

 赵浩民奕君 发布于 2022-12-10 05:33
  • php
  • 尝试访问存储在向量中的对象的方法时遇到麻烦。我知道getEdges返回边缘的无序贴图,但是我缺少关于如何从向量中引用Vertex对象的内容。救命?

    在void UndirectedGraph :: minSpanningTree()中:

    std::vector visited;
    
    if(vertices.begin() != vertices.end())
    {
        visited.push_back(vertices.begin()->second);
        visited[0]->distance = 0;
    }
    else
    {
        return;
    }
    
    std::vector::const_iterator vit;
    vit = visited.begin();
    std::unordered_map edges;
    edges = vit -> getEdges();
    

    在const std :: unordered_map和Vertex :: getEdges()const中:

    return edges;
    

    错误:

     UndirectedGraph.cpp:112:21: error: member reference base type 'Vertex
     *const' is
           not a structure or union
             edges = vit -> getEdges();
                     ~~~ ^  ~~~~~~~~ 1 error generated.
    

    - 编辑 -

    改变中

    edges = vit -> getEdges();
    

    edges = *(vit)->getEdges();
    

    给了我同样的错误。

    1 个回答
    • vit是一个迭代器。迭代的工作方式类似于指向容器元素的指针。您的容器元素类型为Vertex*。因此vitVertex**

      要调用给定的成员函数,Vertex** p您必须先进入Vertex*。可以这样取消引用p

      (*p)
      

      现在您可以像这样调用您的成员函数

      (*p)->getEdges()
      

      迭代器没有什么不同。

      注意

      *(p)->getEdges()
      

      与上述完全不同(而且是错误的)。与...相同

      *((p)->getEdges())
      

      (p)->getEdges()
      

      是相同的

      p->getEdges()
      

      这是行不通的。

      与此相关的是,如果使用原始指针,则可能做错了。您应该将Vertex对象直接存储在中,std::vector<Vertex>或者使用shared_ptrunique_ptr代替原始指针。

      2022-12-11 02:04 回答
    撰写答案
    今天,你开发时遇到什么问题呢?
    立即提问
    热门标签
    PHP1.CN | 中国最专业的PHP中文社区 | PNG素材下载 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
    Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有