2012-05-02 79 views
2

我想爲我的二叉樹創建一個複製構造函數。二叉樹 - 複製構造函數

我的問題:

我可以看到源代碼樹的價值越來越被複制到目標樹,但是當它涉及到的值寫出來,也有複製的樹沒有價值,它崩潰的我程序。

錯誤消息:binTree.exe在0x0097a43c

未處理的異常:0000005:訪問衝突讀取位置0xccccccec。

代碼:

//主要方法

int main(int argc, char **) { 
    ifstream fin6("input_data.txt"); 
    ofstream out9("copied_tree.txt"); 

    if(!fin6.is_open()) 
    { 
     cout << "FAIL" << endl; 
     return 1; 
    } 

    BinaryTreeStorage binaryTreeStorage2; 

    // read in values into data structure 
    binaryTreeStorage2.read(fin6); 

    BinaryTreeStorage binaryTreeStorage3 = binaryTreeStorage2; 

    // output values in data structure to a file 
    binaryTreeStorage3.write(out9); 

    fin6.close(); 
    out9.close(); 

    // pause 
    cout << endl << "Finished" << endl; 
    int keypress; cin >> keypress; 
    return 0; 
} 

//拷貝構造函數

BinaryTreeStorage::BinaryTreeStorage(BinaryTreeStorage &source) 
{ 
    if(source.root == NULL) 
     root = NULL; 
    else 
     copyTree(this->root, source.root); 
} 

//複製樹方法

void BinaryTreeStorage::copyTree(node *thisRoot, node *sourceRoot) 
{ 
    if(sourceRoot == NULL) 
    { 
     thisRoot = NULL; 
    } 
    else 
    { 
     thisRoot = new node; 
     thisRoot->nodeValue = sourceRoot->nodeValue; 
     copyTree(thisRoot->left, sourceRoot->left); 
     copyTree(thisRoot->right, sourceRoot->right); 
    } 
} 

回答

1

如果改變的功能的指針(未指針對象)的值,則必須傳遞給指針的引用:如果一個指針傳遞到一個函數

void BinaryTreeStorage::copyTree(node *& thisRoot, node *& sourceRoot) 

,該指針通過值傳遞。如果您更改指針(它存儲的地址)的值,則此更改在該函數外部不可見(這是您撥打new時發生的情況)。因此,爲了使更改在函數外可見,必須傳遞要修改的指針的引用。

This question詳細解釋它。

+0

我最初交換了引用部分和指針部分。它現在應該工作。 –

+0

完美的作品,非常感謝。 – MitchellT

+0

謝謝你的鏈接,這很好解釋。 – MitchellT