문제

I use composite pattern to implement a tree structure. It has 3 classes: node (base class), leaf (no child class), and branch (with children class). And I have some common data put in a tree node, like the root. An example of the common data is unit choice of meter or kilometer. The common data should be accessed to all the nodes. How to implement it? Putting a pointer of the common data to all the nodes doesn't seem to be memory efficient.

도움이 되었습니까?

해결책

One way to do this is to add a separate class for the tree, put the root pointer there, and add all the common items there as well. Then add a tree pointer to the node base class, and also add a constructor argument to point all nodes of the tree back to their tree object:

class node;
class tree {
    node *root;
    int multiplier; // e.g. 1000 for meters, 1 for kilometers
}
class node {
protected:
    tree *owner;
    node *parent; // parent is NULL for the root
    node(tree *_owner, node *_parent) : owner(_owner), parent(_parent) {}
};
class branch : public node {
    list<node> children;
public:
    branch(tree *_owner, node *_parent) : node(_owner, _parent) {}
    ...
};
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top