我想做以下工作,我正在编写图形库。我希望我的类应该是模板。
template < typename T>
class Graph
{
}这个图形类可以在另一个class Vertex上工作
我应该如何设计这个Vertex类,以便我的任何团队成员都可以使用,并且我不必在class Graph中更改我的实现
基本上,我希望这个Vertex类提供几个成员函数,如getWeight、getvisited、setvisited
因此,只要客户端在这些类中包含这些函数,就可以按原样使用Graph类
发布于 2010-10-05 03:51:31
通常,图类不会做太多事情,因为所有数据都在顶点或边中(取决于由objects表示的对象,- it听起来像是您想要的顶点对象)。
所以,你可能有
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成为获取顶点的唯一方法。
发布于 2010-10-05 05:14:13
定义Vertex接口时,以下方案可能会有所帮助。它将为您提供预先定义签名的能力,以便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();
};https://stackoverflow.com/questions/3858550
复制相似问题