Can a class have a member of its own type?
In order to emulate a containment relationship in which objects contain other instances of the same type, can I defi开发者_运维百科ne a class as such?
class RussianDoll {
string name;
RussianDoll doll;
RussianDoll();
}
How should I build the constructor(s) for this class?
Can a class have a member of its own type?
Sure. It's actually quite common. Think of the case of a node in a linked list for instance:
class Node {
Node next;
int value;
}
How should I build the constructor(s) for this class?
You have several options (see below). You should obviously avoid creating new instances of the class in each invocation of the constructor as it would result in an infinite recursion.
You could take a
Node
as argument and initialize it likethis.next = nextArg;
You could initialize it to the null-reference
this.next = null;
You could initialize it to
this
this.next = this;
(It's generally a bad idea to create a whole object graph inside a constructor any way so I wouldn't worry about this anyway :-)
Sure, why not? As long as you are not instantiating it indefinitely.
class RussianDoll {
RussianDoll parentDoll;
RussianDoll(RussianDoll parentDoll) {
this.parentDoll = parentDoll;
}
}
Yes.
A common example of this is a linked list.
However, you cannot unconditionally create the child in the constructor, or you'll create an infinite number of objects.
精彩评论