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 に答える