【问题标题】:Passing by pointers通过指针传递
【发布时间】:2015-03-28 09:07:23
【问题描述】:

我正在使用 VS13 为学校开发 C++ 程序。我需要将数据插入 BST。我得到了一个定义为 Add(int dataValue); 的函数。 (在 public 下)只取数据值。我定义了第二个 Add() 函数,它也将 Node* 作为参数,以便使 Add() 递归。 (参见下面的 .h 部分代码)

#include <iostream>
#include <queue>

class HW2BST
{
private:
    struct Node
    {
        int Data;
        Node* Left;
        Node* Right;

        Node(int dataValue);
    };

    Node* m_root;

    bool Add(Node* root, int dataValue);

public:
    bool Add(int dataValue);

我的问题是,当从 main 调用 tree.Add(int) 时,我尝试将 m_root 传递给第二个 Add(Node*, int) 函数以插入数据。单步执行该函数并观察 m_root 和 root 运行时,我看到 Add(Node*, int) root 内部设置为 NULL,如我所料。当它逐步通过 root->Data 时,dataValue 被正确分配,并且 root->Left 和 root->Right 被正确分配为 NULL。但是这些分配不会传回给 m_root。一旦函数退出,root 就会被销毁,m_root 不会更新,我就没有树了。 (参见下面的 .cpp)

#include "HW2BST.h"

using namespace std;

HW2BST::Node::Node(int dataValue)
{
    Data = dataValue;
    Left = Right = NULL;
}

HW2BST::HW2BST(void)
{
    m_root = NULL;
}

bool HW2BST::Add(int dataValue)
{
    return Add(m_root, dataValue);          // Add (overload) recursively searches then inserts dataValue, then returns result
}

bool HW2BST::Add(Node* root, int dataValue)
{
    if (!root)                              // verify if node exists
    {
        root = new Node(dataValue);         // if node does not exist, implement new node and set dataValue
        if (!root)                          // if node not allocated correctly, return false
            return false;
        else                                // else return true (both new node implemented and value added to tree)
            return true;
    }
    else if (dataValue < root->Data)            // if not empty, check data value with current data
        return Add(root->Left, dataValue);      // if less than, travel down left child
    else if (dataValue > root->Data)
        return Add(root->Right, dataValue);     // if greater than, travel down right child
    else
        return false;                           // if equal to, ignore (double entry)
}

我已经和我的教授谈过了,他说了一些关于使用 Node** 的事情,但是当我尝试时我无法让类型协调(即 root->Data 不断抛出错误 C2227)。

我知道解决方案很简单,但我似乎无法理解我所缺少的。

【问题讨论】:

    标签: c++ pointers


    【解决方案1】:

    这是一个有问题的行:

    root = 新节点(dataValue);

    这是有问题的,因为 C++ 默认按值传递参数,指针也是如此。这意味着函数root内部是原始指针的副本,更改副本当然不会更改原始指针。

    你需要通过引用传递指针

    bool Add(Node*& root, int dataValue);
    

    您当然可以 emulate 使用指针通过引用传递,就像在 C 中所做的那样,但是您必须记住取消引用指针以及在何时使用地址运算符 &amp;传递指针。但由于 C++ 有适当的引用,因此不需要。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-07-27
      • 2023-03-03
      • 2018-08-19
      • 1970-01-01
      • 1970-01-01
      • 2019-09-16
      • 2021-02-28
      相关资源
      最近更新 更多