函数参数 - 指针还是指向指针的引用?

3
void DeleteChildren(BSTNode *node)
{
    // Recurse left down the tree...
    if(node->HasLeftChild()) DeleteChildren(node->GetLeftChild());
    // Recurse right down the tree...
    if(node->HasRightChild()) DeleteChildren(node->GetRightChild());

    // Clean up the data at this node.
    node->ClearData(); // assume deletes internal data

    // Free memory used by the node itself.
    delete node;
}

// Call this from external code.
DeleteChildren(rootNode);

这个函数是递归删除二叉搜索树。

我对第一行中的 BSTNode *node 有疑问,我是否需要将其修改为 BSTNode *& node ?


你对代码有问题吗?让你觉得有什么不对劲?在我看来它很好。 - Kai
4个回答

3

只有在想要更改指针指向的内容时,才需要通过引用传递指针。如果您想要将节点设置为NULL,则需要将其作为BSTNode*&传递。


2

不,指针是按值传递的,所以当你将它作为参数传递时,实质上是在“复制”指针。只有当你想让被调用者修改调用者的参数时,才使用按引用传递。


0

不需要这样做。您在DeleteChildren函数中提供的指针将被删除,因此rootNode也将被删除。

如果您需要修改存储rootNode的地址,则参数可以是BSTNode *&类型。但在这种情况下,您不需要这样做。


0

不是。假设rootNode也是BSTNode*类型,那么rootNodenode都指向同一块内存地址。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接