简体   繁体   English

嵌套的结构和指针

[英]nested structs and pointers

I am learning about nested structures and came across the following code: 我正在学习嵌套结构,并遇到了以下代码:

// Stack.h

#ifndef STACK_H
#define STACK_H

struct Stack{
    struct Link{
        void* data;
        Link* next;
        void initialize(void* dat, Link* nxt);
    }* head;
    void initialize();
    void push(void* dat);
    void* peek();
    void* pop();
    void cleanup();
};

#endif // STACK_H

the Link structure is within the scope of Stack and to access Link I would have to use Stack::Link. Link结构在Stack的范围内,要访问Link,我必须使用Stack :: Link。

I am a bit confused about the pointer head that is declared after the } to close the Link struct. 对于在}之后声明以关闭Link结构的指针头,我有些困惑。

Does this mean that there is a Link pointer variable named head inside the Stack scope? 这是否意味着在Stack范围内有一个名为head的Link指针变量?

What is the effect of defining the head pointer as: 将头指针定义为以下内容有什么作用:

};
Link* head;

vs

}* head; //as per the code above?

There is no difference. 没有区别。 Both declarations result in a Stack::head member of type Stack::Link* . 这两个声明都会导致Stack::head Stack::Link*类型的Stack::head成员。

Does this mean that there is a Link pointer variable named head inside the Stack scope? 这是否意味着在Stack范围内有一个名为head的Link指针变量?

Yes, that's exactly right. 是的,完全正确。

As to your second question, there is no semantic difference between the two styles of declaration. 关于第二个问题,两种声明样式之间没有语义上的区别。

Its just a short hand for the semantic. 它只是语义上的简写。 like how we use += . 就像我们使用+= And yes you have a local pointer variable. 是的,您有一个本地指针变量。

struct Stack{
    struct Link{
        void* data;
        Link* next;
        void initialize(void* dat, Link* nxt);
    };

    Link* head;  //Same as code as in your program
    void initialize();
    void push(void* dat);
    void* peek();
    void* pop();
    void cleanup();
};

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

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