C++将具有非常相关数据的类 Tree 拆分为两个类

C++ split class Tree with a very related data into two classes

本文关键字:拆分 Tree 两个 非常 数据 C++      更新时间:2023-10-16

我有一个类Tree

class Tree {
    string aboutTree;
    vector<int> veryImportantInfo;
    Tree* leftChild;
    Tree* rightChild;
    ...
    void veryImportantMethod() {
        // change and use aboutTree
        // change and use veryImportantInfo
    }
};

aboutTreeveryImportantInfo 不是恒定的,但对于树的所有节点都是相同的,我不想在所有节点中复制它。我想要这样的东西:

class Tree {
    //string aboutTree;
    //vector<int> veryImportantInfo;
    Tree* leftChild;
    Tree* rightChild;
    ...
    void veryImportantMethod() {
        // change and use aboutTree
        // change and use veryImportantInfo
    }
};
class TreeWrapper {
    string aboutTree;
    vector<int> veryImportantInfo;
    Tree root;
    ...
};

但是不是工作,因为我无法访问TreeWrapper的非静态字段。

我想出的一个可能的粗略解决方案是让所有分支链接回包装器并直接访问数据:

注意我Tree替换TreeWrapperbranch替换Tree因为这对我来说更有意义。

class tree
{
public:
    struct branch
    {
        branch* leftChild;
        branch* rightChild;
        tree* parent;
        void veryImportantMethod() {
            // change and use parent->aboutTree
            // change and use parent->veryImportantInfo
        }
    };
    tree() { root.parent = this; }
    tree root;
    string aboutTree;
    vector<int> veryImportantInfo;
};

每当您创建新branch时,您都需要leftChild->parent = parent; . 您还需要定义 branch 的成员函数来为您执行此操作,就像在双向链表中一样。

另一种解决方案是使用实际的双向链表格式。所以tree* parentbranch* parent. 从分支访问重要信息不会像上面那么快,但这意味着它将更易于导航。你可以更容易地绕着树走。 (实际上,同时拥有tree* rootbranch* parent可能不是一个坏主意。但更精细的细节取决于你。