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
?
Link
is declared inside Stack
, and since it's private
by default, it can't be used outside the class.
Also, Stack
has a member head
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 "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".
Class Stack
and struct Link
are nested.
Note that nested classes have certain limitations regarding accessing of elements of nested and the enclosing class.
Since, Link
is declared under private
access specifier in class Struct
it cannot be accessed outside the class Struct
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With