我有一个课程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的非静态字段。

最佳答案

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

注意,我用TreeWrapper替换了Tree,用Tree替换了branch,因为这对我来说更有意义。

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* parent将是branch* parent。从分支机构访问重要信息的速度不会像上面那样快,但这意味着它更易于导航。您可以更轻松地在树上四处走动。 (实际上同时具有tree* rootbranch* parent可能不是一个坏主意。但是,更详细的信息取决于您。)

09-10 01:31
查看更多