简体   繁体   English

关于C ++中的节点的错误

[英]error about a node in C++

I got this error and I dont know how to fix it. 我收到此错误,我不知道如何解决。

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

my code where the error is. 错误所在的代码。

//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;
}
                             ^

This error comes from the strangeness that is declaring an object with the same name as its type: 此错误来自于奇怪的情况,该异常声明了一个与它的类型同名的对象:

node *node = new node;

Not only is this extremely confusing to readers of your program, but now on the RHS the word node means the object, not the type. 这不仅使程序的读者非常困惑,而且现在在RHS中,单词node表示对象,而不是类型。 So new node becomes invalid. 因此, new node无效。

The error message is kindly informing you that you can make node refer to the type by writing struct before it: 该错误消息谨通知您,可以通过在node之前编写struct来使node引用该类型

node* node = new struct node;

This works because, when T is a class type, struct T always means that class type T and cannot mean anything else. 之所以起作用是因为,当T是类类型时, struct T始终表示该类类型T而不能表示其他任何内容。

But, honestly, simply do not do this . 但是,老实说, 根本不要这样做 Use better names. 使用更好的名字。

You have declared a variable called node . 您已经声明了一个名为node的变量。 That is the name of a type you're intending to use after that declaration. 这是您打算在该声明之后使用的类型的名称。 So you need to specify that you're referring to the type, not the variable by using struct or class appropriately. 因此,您需要通过适当地使用structclass来指定要引用的类型,而不是变量。

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

The better solution would be to use a different name for the variable. 更好的解决方案是为变量使用其他名称。

node* n = new node;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM