2010-10-04 81 views
0

我想要做下面的事情,我在写Graph库。我想我的课应该是模板。C++设计模式暗示

template < typename T> 
class Graph 
{ 
} 

这Graph类适用于另一个class Vertex

我应该如何设计这个Vertex类,以便任何我的团队成员都可以使用,我没有改变class Graph

基本上我的实现我希望这个Vertex类提供几个成员函数,如getWeight,getvisited,setvisited

所以只要客户端具有这些功能,那么类Graph类可以按原样使用

+1

你看过Boost Graph吗? http://www.boost.org/doc/libs/release/libs/graph – Potatoswatter 2010-10-04 19:48:40

+0

你的意思是'Graph '将使用特定的类'Vertex'作为成员或方法参数?或者你的意思是'图'应该被允许,只要'顶点'提供某些接口方法? – aschepler 2010-10-04 19:49:03

+0

是aschepler,这是我正在寻找。 – Avinash 2010-10-04 19:50:00

回答

1

通常,图类没有太大的作用,因为所有的数据都在顶点或边缘(取决于哪个由对象表示 - 这听起来像你想要的顶点对象)。

所以,你可能有

template< typename T > 
struct Vertex { 
    bool visited; 
    T data; 

    vector< Vertex * > edges; 

    size_t getWeight() const { return edges.size(); } 

    bool getvisited() const { return visited; } 
    void setvisited(bool v) { visited = v; } 
}; 

您可能希望在图形玻璃将自己所有的顶点,并试图摧毁它时,防止断线或周期的问题。

template< typename T > 
struct Graph { 
    typedef Vertex<T> vertex_t; 
    deque<vertex_t> vertices; 

    vertex_t &get_vertex() { 
     return * vertices.insert(vertices.end(), vertex_t()); 
    } 
}; 

...和做的Vertex私有的构造函数,和图形及其friend,使Graph获得顶点的唯一途径。

0

在定义顶点界面时,以下情况可能会有所帮助。它将使您能够预先定义签名,以便Graph能够编译以及让用户通过继承来扩展Vertex以满足其需求(如果这是您的目标之一)。

// Interface only (i.e. pure virtual). The user must implement this method 
// but the signature is defined up front so Graph able to call it. 
class Vertex { 
    public: 
    virtual int getWeight() = 0; 
}; 

// Interface with a default implementation (i.e. virtual). The default 
// implementation is provided by you but the user can override the 
// implementation if needed. 
class Vertex { 
    public: 
    virtual int getWeight(); 
}; 

// Interface has a required implementation (i.e. non-virtual). The user 
// should not override your implementation. 
class Vertex { 
    public: 
    int getWeight(); 
};