いいえ、そのような構造を持つことはできないからです。それは無限に大きくなります(anode
には2つの子node
があり、それぞれに2つの子がありますnode
。など)。これが、同じタイプの子を持つノードを作成するときに人々がポインターを使用する理由です。
たとえば、それを行わない方法:
/* This is a problem because of the recursive nature of the structure. leftChild also
contains a leftChild itself, which also contains a leftChild, etc. forever. */
struct node
{
node leftChild; // how big is leftChild? infinitely large!
node rightChild; // how big is rightChild? infinitely large!
int data;
}
そしてそれを行う正しい方法:
/* This is not a problem because the size of a pointer is always 4 bytes (assuming 32-
bit system). You can allocate room for the child nodes without recursively requiring an
infinite amount of memory. */
struct node
{
node* leftChild; // how big is leftChild? 4 bytes (assuming 32-bit system)
node* rightChild; // how big is rightChild? 4 bytes (assuming 32-bit system)
int data;
}
あなたがそれを正しい方法でやったら、言うことは完全に合法です:
void foo(node head)
{
std::cout << head.leftChild->data; // assuming leftChild points to a valid object!
}