I am not very clear about this code
outer is a class and the inner a struct, can anyone help me explain it?
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 is focus on the first few lines
class Stack {
struct Link {
void* data;
Link* next;
Link(void* dat, Link* nxt):
data(dat),next(nxt) {}
}* head;
what the relation between class Stack and struct Link?
Linkis declared insideStack, and since it’sprivateby default, it can’t be used outside the class.Also,
Stackhas a memberheadwhich is of typeLink*.The only difference between
classandstructis the default access level –publicfor struct andprivatefor class, so don’t let “struct declared inside a class” confuse you. Other than the access level, it’s the same as “class declared inside a class” or “struct declared inside a struct”.