Previous: Linked List with global pointers Up: Examples
enum Tree_type{no_children,left_child_only,right_child_only,both_children}; struct Tree { int data; Tree_type info; Tree* left_child; Tree* right_child; Tree() {} // Default constructor to be called before {\tt operator>>} friend CCVoid& operator<<(CCVoid&,const Tree&); friend CCVoid& operator>>(CCVoid&,Tree&); };
The transfer functions might be written as follows:
CCVoid& operator<<(CCVoid& v,const Tree& in) { int info = in.info; v << info; // Transfer the enumerated type as an integer v << in.data; switch (in.info) { case no_children: break; case left_child_only: v << *(in.left_child); break; case right_child_only: v << *(in.right_child); break; case both_children: v << *(in.left_child) << *(in.right_child); break; } return v; }CCVoid& operator>>(CCVoid& v,Tree& out) { int info; v >> info; out.info = (Tree_type)info; v >> out.data; switch (out.info) { case no_children: out.right_child = out.left_child = 0; break; case left_child_only: out.right_child = 0; out.left_child = new Tree(); v >> *(out.left_child); break; case right_child_only: out.left_child = 0; out.right_child = new Tree(); v >> *(out.right_child); break; case both_children: out.left_child = new Tree(); v >> *(out.left_child); out.right_child = new Tree(); v >> *(out.right_child); break; } return v; }
Again, the unpacking function initializes the already allocated object out. The packing and unpacking functions agree to use prefix notation for the tree, and to preface each data value with information about what, if any, children that node has.