C++ 结构创建错误没有命名类型

C++ Struct creation error does not name a type

当我运行我的程序时,每次使用temp->时都会出现以下错误。

[错误] 请求“* temp”中的成员 'key',它是指针类型 'NodeType {aka Node*}'(也许您打算使用“->”?)

代码有什么问题。

struct Node;
typedef Node *NodeType;

int NumNodes = 0;
const int SIZE = 100;
NodeType data[SIZE];


struct Node{
int key;
NodeType *left, *right;
};

NodeType *newNode(int value){
  if(NumNodes == SIZE)
    cout << "This Node Pool is full." << endl;
    exit(1);

  NodeType *temp = &data[NumNodes++];
  temp->key  = value;                  
  temp->left = temp->right = NULL;     
  return temp;
}

如果我们去掉令人困惑的 typedef,这就是您所拥有的:

struct Node;

int NumNodes = 0;
const int SIZE = 100;
Node* data[SIZE];

struct Node{
    int key;
    Node **left, **right;
};

Node** newNode(int value){
  if(NumNodes == SIZE)
    cout << "This Node Pool is full." << endl;
    exit(1);

  Node** temp = &data[NumNodes++];
  temp->key  = value;                  
  temp->left = temp->right = NULL;     
  return temp;
}

如您所见,您添加了一个(不必要的)间接级别,将指针存储到树中的指针,并拥有 Node 个指针池而不是 Node 个指针池s.

删除 typedef 并使用 Node 代替 NodeType:

struct Node{
    int key;
    Node *left, *right;
};

int NumNodes = 0;
const int SIZE = 100;
Node data[SIZE];


Node* newNode(int value){
  if(NumNodes == SIZE) {
    cout << "This Node Pool is full." << endl;
    exit(1);
  }

  Node* temp = &data[NumNodes++];
  temp->key  = value;                  
  temp->left = temp->right = NULL;     
  return temp;
}

您对指针感到困惑。首先摆脱 NodeType 并使用 Node* 代替。知道程序中的指针在哪里很重要,将它们隐藏在 typedef 后面对您没有任何好处。

现在是真正的错误。您正在尝试创建一个用于分配的对象池。所以池应该是对象而不是指针。

int NumNodes = 0;
const int SIZE = 100;
Node data[SIZE];

现在你的分配函数应该return一个指向池中对象的指针。在您的代码中,它 returns NodeType* 是一个 指向指针 的指针(因为 NodeType 是一个指针)。同样非常重要的是,您在 newNode 中的 if 语句周围缺少大括号(对 exit 的调用不在代码中的 if 语句内)。所以改为

Node *newNode(int value) {
    if (NumNodes == SIZE) {
        cout << "This Node Pool is full." << endl;
        exit(1);
    }
    Node *temp = &data[NumNodes++];
    temp->key  = value;                  
    temp->left = temp->right = NULL;     
    return temp;
}

最后你的 struct 也有指向指针的指针,而它应该只有普通的指针

struct Node{
    int key;
    Node *left, *right;
};

基本上,您通过将 NodeType 声明为指针然后在顶部添加另一个指针,在自己的脑海中制造了很多混乱。

struct Node
{
int key;
Node *left, *right;
};

int NumNodes = 0;
const int SIZE = 100;
Node data[SIZE];

Node* nNode(int value)
{

if(NumNodes == SIZE)
{
    cout << "This is full" << endl;
    exit(1);
}
else
{        
    Node* temp = &data[NumNodes++];
    temp->key  = value;                  
    temp->left = temp->right = NULL; 
    return temp;
}
}