2012-07-16 56 views
1

這裏是我的類:實現在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’ 

是什麼原因造成問題?

+0

朋友類聲明不完整。你需要指定Graph 而不是Graph。 – Chethan 2012-07-16 04:44:00

回答

3

你有一個朋友語句中使用時,它以「前進申報」 Graph類:

template <class T> 
class Graph; 

template <class T> 
class Vertex 
{ 
private: 
//... 
public: 
friend class Graph<T>; 
// ... and so on 
2

正如錯誤消息所述,您需要爲使用Graph類的任何位置提供模板參數。因此,友元類聲明應該有

friend class Graph<T>; 

而不是

friend class Graph; 
+0

圖而不是Graph? – 2012-07-16 04:46:37

+0

幾個字符丟失了...編輯,感謝指出。 – Jari 2012-07-16 04:49:15

0

事實上,不需要前向聲明。如果尚未定義類或函數,則朋友聲明會創建前向聲明。標準明確指出這一點。你應該寫:

template <class T> friend class Graph; 

這將有效申報的Graph所有實例作爲當前類的朋友。