C 中关于节点的错误

error about a node in C++

本文关键字:节点 错误 于节点      更新时间:2023-10-16

我有这个错误,我不知道如何修复它。

error: must use 'struct' tag to refer to type 'node' in this scope
            node *node = new node;

我的代码在哪里。

//New empty tree
struct node *newTreeNode(int data)
{
    //New tree nodes
    node *node = new node;
    //New data node
    node->data = data;
    //New left node
    node->left = nullptr;
    //New right node
    node->right = nullptr;
    return node;
}
                             ^

此错误来自于声明具有与其类型相同名称的对象的陌生性:

node *node = new node;

这不仅对您程序的读者感到非常困惑,而且现在在RHS上,node一词表示对象,而不是类型。因此new node变得无效。

错误消息会通知您,您可以通过在 type 上写下struct来进行node

node* node = new struct node;

这有效,因为当T是类类型时,struct T总是表示类型T,并且不能含义其他任何内容。

但是,老实说,根本不这样做。使用更好的名称。

您已声明了一个称为node的变量。那是您打算在该声明之后使用的类型的名称。因此,您需要指定您指的是类型,而不是通过适当使用structclass的变量。

node *node = new struct node;
                 ^^^^^^

更好的解决方案是为变量使用其他名称。

node* n = new node;