Cluster and structure

I do not really understand this code

external is a class , and internal is a struct , can someone help me explain this?

 class Stack { struct Link { void* data; Link* next; Link(void* dat, Link* nxt): data(dat),next(nxt) {} }* head; public: Stack():head(0) {} ~Stack() { require(head==0,"Stack not empty"); } void push(void* dat) { head = new Link( dat, head ); } void peek() const { return head ? head->data : 0; } void* pop() { if(head == 0) return 0; void* result = head->data; Link* oldHead = head; head = head->next; delete oldHead; return result; } }; 

my question focuses on the first few lines

 class Stack { struct Link { void* data; Link* next; Link(void* dat, Link* nxt): data(dat),next(nxt) {} }* head; 

what's the relationship between class Stack and struct Link ?

+4
source share
3 answers

Link declared inside Stack , and since it is private by default, it cannot be used outside the class.

In addition, Stack has a member member, which is of type Link* .

The only difference between class and struct is the default access level - public for struct and private for class, so don't let the "structure declared inside the class" confuse you. Besides the access level, it is the same as "a class declared inside a class" or "a structure declared inside a structure".

+5
source

The Stack class and struct Link nested .
Note that nested classes have certain restrictions regarding access to elements of a nested and enclosing class.

Since Link declared in the private access specifier in the Struct class, it cannot be accessed outside the Struct class.

+4
source

Struct Link is internally declared in the class (the correct term is nested). Access to it is possible only in the classroom (due to its usual level of access to accessories). A structure could be passed using Stack::Link if it was declared public.

The reason for this declaration in this case is that only the internal methods of the class should use references, and struct provides a better organization of the code. However, as long as some other class does not have to access the struct , such a declaration provides better encapsulation.

+1
source

Source: https://habr.com/ru/post/1403870/


All Articles