[英]C++ Member Reference base type 'Vertex *const' is not a structure or union
嘗試訪問存儲在向量中的對象的方法時遇到麻煩。 我知道getEdges返回邊緣的無序貼圖,但是我缺少如何從向量中引用Vertex對象的東西。 救命?
在void UndirectedGraph :: minSpanningTree()中:
std::vector<Vertex*> visited;
if(vertices.begin() != vertices.end())
{
visited.push_back(vertices.begin()->second);
visited[0]->distance = 0;
}
else
{
return;
}
std::vector<Vertex*>::const_iterator vit;
vit = visited.begin();
std::unordered_map<std::string, Edge> 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();
給了我同樣的錯誤。
vit
是一個迭代器。 迭代的工作方式類似於指向容器元素的指針。 您的容器元素類型為Vertex*
。 因此, vit
工作方式類似於Vertex**
。
要調用給定Vertex** p
的成員函數,您必須先進入Vertex*
。 可以這樣取消p
的引用:
(*p)
現在您可以像這樣調用您的成員函數
(*p)->getEdges()
迭代器沒有什么不同。
注意
*(p)->getEdges()
與上述完全不同(而且是錯誤的)。 與...相同
*((p)->getEdges())
和
(p)->getEdges()
是相同的
p->getEdges()
這是行不通的。
與此相關的是,如果使用原始指針,則可能做錯了。 您應該將Vertex
對象直接存儲在std::vector<Vertex>
或者使用shared_ptr
或unique_ptr
代替原始指針。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.