【问题标题】:Binary Tree - Copy Constructor二叉树 - 复制构造函数
【发布时间】:2012-05-02 10:59:51
【问题描述】:

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

我的问题:

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

错误信息:

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);
    }
}

【问题讨论】:

    标签: c++ constructor tree copy binary-tree


    【解决方案1】:

    如果你在函数中改变一个指针(不是指针)的值,你必须传递一个对该指针的引用:

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

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

    This question详细解释。

    【讨论】:

    • 我最初交换了引用部分和指针部分。它现在应该可以工作了。
    • 也感谢您提供的链接,这很好地解释了它。
    猜你喜欢
    • 1970-01-01
    • 2018-09-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-28
    • 1970-01-01
    • 2021-11-25
    相关资源
    最近更新 更多