【发布时间】:2010-02-11 10:32:43
【问题描述】:
我想知道:
对于一棵树,根可以有多个孩子并且没有 id。所有节点(根节点除外)都有一个 id,叶节点不能有子节点。每个深度必须使用什么类型是固定的。所以叶子总是相同的类型,叶子的父母也是。
由于根和节点可以有子节点,并且只有节点有 id,所以我想知道以下多重继承的使用是否可以接受:
class NodeWithId
{
private:
std::string m_id;
};
template<typename T>
class NodeWithChildren
{
private:
std::vector<T> m_nodes;
};
class Network: public NodeWithChildren<Subnet>
{
};
class Subnet: public NodeWithChildren<Machine>,
public NodeWithId
{
};
class Machine: public NodeWithChildren<Application>,
public NodeWithId
{
};
class Application: public NodeWithId
{
};
或者有没有更好的方法来实现这个?
编辑:
- 删除了虚拟
- 更改了类名
【问题讨论】:
-
为什么要使用虚拟继承?在任何继承路径中都没有共享基类。
-
我会为所有类型的节点使用一个类,只在根中使用一个虚拟 id,在叶子中使用空子向量
-
我同意 Manuel 的观点 - 使用 -1 或 0 或其他保留值作为根的 ID,并简化您的设计。
标签: c++