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. So new node
becomes invalid.
The error message is kindly informing you that you can make node
refer to the type by writing struct
before it:
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.
But, honestly, simply do not do this . Use better names.
You have declared a variable called 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.
node *node = new struct node;
^^^^^^
The better solution would be to use a different name for the variable.
node* n = new node;
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.