0

我有以下类型:

typedef std::vector<Node> Nodes;
struct Top: public Nodes {};
struct Middle: public Nodes {};
struct Bottom: public Nodes {};

现在假设我的测试类构造了一个Nodes名为_standardNodes

TestDifferentTypes(): _standardNodes(standardNodes(_model)) 
{
}

如何创建使用存储在节点中的数据初始化的 Top 实例?

4

3 回答 3

2

继承向量不是一个好主意;你想在那里有一个关系,而不是是一个。使用具有的父级并从中class NodeStore继承所有其他节点类。 std::vectorNode

然后编写一个适当的构造函数(对于每个类),它接受您需要的每种对象类型。它可能看起来像这样:

class NodeStore {
    std::vector<Node> m_nodes;

    std::vector<Node>& getNodes() { return m_nodes; }
}

class TopNode {
  TopNode ( NodeStore& store ): m_nodes(store.getNodes()) 
  {
  }

}
于 2013-01-28T10:51:36.450 回答
0

You haven't shown us the use of Nodes and Top, Middle and Bottom, but from the looks of things, I don't think this can be made to work, for several reasons.

The most important reason is simple: a std::vector<Node> can only contain objects of type Node. Objects of type Top, Middle and Bottom will be sliced (converted to Node) if inserted, so you loose the derived type.

And you cannot do something like struct Top : public std::vector<Top> (not that I think that's what you want), since you cannot instantiate a vector over an incomplete type, and you cannot derive from an uninstantiated template.

The usual solution for this is to create a Tree class, and use std::vector<Node*> in the nodes (as a member, not via inheritance). Alternatively, you can use Boost's pointer vector (but be careful of lifetime of the objects), or if you know that you'll never need back pointers, you can use std::vector<std::unique_ptr<Node>> (but the interface becomes a little trickier, and you still need to be careful about the lifetime of objects—removing an object from the tree will destroy it).

于 2013-01-28T11:00:21.240 回答
0

通常避免从容器类型继承(例如,析构函数未声明为虚拟的,这意味着您需要小心多态性)。您应该更喜欢组合

但是,要回答您的问题,您需要定义一个适当的构造函数Top,然后在其中调用适当的基类构造函数:

struct Top : public Nodes {
    Top(const Nodes &rhs) : Nodes(rhs) {}
    ...
};
于 2013-01-28T10:50:57.153 回答