[英]Implementing a graph class in C++
這是我的課:
template <class T>
class Vertex
{
private:
T data;
Vertex<T>* next;
public:
friend class Graph;
Vertex(T dat, Vertex<T>* nex)
{
data=dat; next = nex;
}
};
template <class T>
class Graph
{
public:
Vertex<T>* head;
Graph() : head(NULL)
{
}
void insert(T data)
{
Vertex<T>* ptr = new Vertex<T>(data, head);
head = ptr;
}
};
主要:
int main()
{
Graph<int> graph;
graph.insert(1);
}
當我編譯時,它告訴我:
graph.h: In instantiation of ‘Vertex<int>’:
graph.h:30: instantiated from ‘void Graph<T>::insert(T) [with T = int]’
main.cpp:6: instantiated from here
graph.h:10: error: template argument required for ‘struct Graph’
是什么導致此問題?
在朋友聲明中使用Graph
類時,必須“預先聲明”它:
template <class T>
class Graph;
template <class T>
class Vertex
{
private:
//...
public:
friend class Graph<T>;
// ... and so on
如錯誤消息所述,無論您在哪里使用它,都需要為Graph類提供模板參數。 所以,朋友類聲明應該有
friend class Graph<T>;
代替
friend class Graph;
實際上,不需要前向聲明。 如果尚未定義類或函數,則朋友聲明會創建前向聲明。 標准明確指出了這一點。 您應該寫:
template <class T> friend class Graph;
這將有效地將Graph
所有實例聲明為當前類的朋友。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.