2013-09-25 36 views
0

我有一個類TreeC++拆分類樹非常相關的數據分爲兩類

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

+0

你可以在你的'main'函數中顯示你的代碼嗎? – prehistoricpenguin

回答

1

我想出了機智h將可能原油的解決方案是讓所有分支機構鏈接回包裝和直接訪問數據:

注我更換TreeWrapperTreeTreebranch,因爲它對我更有意義。

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可能不是一個壞主意,但更好的細節取決於你。)

+0

非常感謝!我使用了你的第一個解決方案。 – avalanche