3

我正在尝试为我的二叉树创建一个复制构造函数。

我的问题:

我可以看到源树的值被复制到目标树中,但是在写出值时,复制的树中没有值,它崩溃是我的程序。

错误信息:

binTree.exe 中 0x0097a43c 处的未处理异常:0xC0000005:访问冲突读取位置 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);
    }
}
4

1 回答 1

3

如果在函数中更改指针(而不是指针)的值,则必须传递对该指针的引用:

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

如果将指针传递给函数,则此指针按值传递。如果您更改指针的值(它存储的地址),则此更改在函数外部不可见(这是您调用 时发生的情况new)。因此,要使更改在函数外部可见,您必须传递对要修改的指针的引用。

这个问题详细解释了它。

于 2012-05-02T11:02:06.420 回答