2011-04-09 136 views
0

我有一個類型模板類的向量,我試圖打印它,但得到一個奇怪的錯誤。在控制檯上打印矢量

這裏是我的類:

template <typename VertexType, typename EdgeType> class Vertex{ 
private: 
    typedef std::vector<std::pair<int, EdgeType> > VertexList; 
    std::vector<Vertex<VertexType, EdgeType>> Vertice; 

public: 
    void Add(Vertex); 
}; 

添加方法和打印聲明:

template <typename VertexType, typename EdgeType> void Vertex<VertexType, EdgeType> ::Add(Vertex v) 
{ 
    int count = 5; 
    //std::vector<string>temp; 

    for(int i=0; i<count; i++) 
    Vertice.push_back(v); 

    for(int i=0; i<Vertice.size(); i++) 
     cout<< Vertice[i] <<endl; 
} 

main()方法:

int main() 
{ 
    Vertex<std::string, std::string> v1; 

    v1.Add(v1); 

    std::getchar(); 
} 

錯誤我得到的是:

error C2679: binary '<<' : no operator found which takes a right-hand operand of type 'Vertex' (or there is no acceptable conversion)

+0

錯 - >'typedef std :: vector VerticeList; .... ....你認爲'typename'是一個類型? – Nawaz 2011-04-09 15:54:40

+0

哦,我不使用那個矢量,因爲它現在是任何地方......我會評論這一點。 – 2011-04-09 15:55:20

+1

你沒有評論。 – Nawaz 2011-04-09 15:56:00

回答

1

你沒有在任何地方定義運算符< <。你應該像你這樣定義它:

template <typename VertexType, typename EdgeType> 
std::ostream& operator << (std::ostream& out, const Vertex<VertexType,EdgeType>& v); 
// implementation 
template <typename VertexType, typename EdgeType> 
std::ostream& operator << (std::ostream& out, const Vertex<VertexType,EdgeType>& v) { 
    // print whatever you want that represents your vertex 

    // please don't forget to return this reference. 
    return out; 
} 

此外,有一個與它的實例向量類是一個麻煩呼叫。請記住,「矢量< Vertice < VertexType,EdgeType > >」是實例的數組,而不是引用數組。如果你想要一個'引用'到Vertex的數組,使用一個指針數組。

考慮使用boost的圖庫,而不是重新定義另一個圖形庫,並陷入與圖形相關的所有陷阱(比如內存管理)。 boost庫也有一些有用的算法,你可以使用..

+0

之間的空格感謝您包含代碼示例。你注意到的代碼,原型可以在類聲明中聲明爲靜態的朋友嗎?這樣,實現實際上可以使用頂點的所有成員。 – sehe 2011-04-09 16:37:12

+0

大多數運算符<<我在那裏寫出來並不需要朋友聲明。大多數時候公共訪問者足以展示有價值的信息。如果不是,那麼我覺得設計有點可疑:爲什麼我應該顯示對於該類用戶不可用的值? – BatchyX 2011-04-09 20:33:50

+0

嘿BatchyX,我試過你的代碼...我得到一些語法錯誤:錯誤C2143:語法錯誤:在'<' – 2011-04-09 20:42:18

0

那麼,實施template <class V, class E> std::ostream& operator<<(std::ostream& os, const Vertex<V,E> &vertex)作爲Vertex的靜態朋友。這幾乎是編譯器告訴你的......