gpt4 book ai didi

c++ - 如何在树结构中获取ansestor的属性?

转载 作者:太空宇宙 更新时间:2023-11-04 11:47:56 25 4
gpt4 key购买 nike

我使用 composite pattern实现树结构。它有 3 个类:节点(基类)、叶子(没有子类)和分支(有子类)。我将一些常用数据放在树节点中,例如根。公共(public)数据的一个例子是米或公里的单位选择。公共(public)数据应该被所有节点访问。如何实现?将公共(public)数据的指针放置到所有节点似乎不是内存有效的。

最佳答案

实现此目的的一种方法是为树添加一个单独的类,将 root 指针放在那里,并在那里添加所有公共(public)项。然后添加一个指向node基类的tree指针,同时添加一个构造函数参数将树的所有节点指向它们的tree对象:

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) {}
...
};

关于c++ - 如何在树结构中获取ansestor的属性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19341005/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com