c++11 - Friend methods in hierarchical structures using C++ -


I am currently implementing some kind of hierarchical structure and if I am attached to the child, then my parents The unit needs to be handed over to the parents. My question is if I can solve this problem by using a friend method in the original code and if it's a good coding style, I understand what I mean:

  class node {node * guardian; Node (): Guardian (Nalphter) {} Friend Zero Attachment (Constell Node and Child) Constance; Friend zero delete child (unsigned long idx) const; }; Class listnode: public node {std :: vector & lt; Node *> children; ListNode (): node () {the-> Childs = {}; } Zero Attach (node ​​* child) const {child-> parent = this; Childs.push_back (child); } Zero delete child (unsigned long idx) const {child-> Parent = nullptr; Child.erase (child.begin () + idx)}}; Class node: public node {}; Class nodules: public nodes {}; Class nodetry: public node {};  

And one last tip: The institution of a child can be clearly a basic unit, whereas children and parents can be of the same type of my scenario.

Yes , in this case it's a bad coding style. Generally, information about parents / child relationships for such genealogy structures is kept in the node.

ListNode class is redundant, and its functionality is actually related to node, which is why you need a friend yourself.

You can use friend functions by simply adding a setParent method to the node class. If you want to make sure that only nodes can move with parents / child relationships, then make it private / protected.

  class node {public: node (): parent (nullptr) {}; Int addChild (node ​​* child) {child-> SetParent (this); This- & gt; Children.push_back (child); Int idx = this- & gt; Children.size () - 1; Return idx; }; Zero removal child (unsigned long idx) {node * kids = children.at (idx); Baby & gt; SetParent (nullptr); This- & gt; Children.rez (kids.bizin (+ +) idx); } Private: Zero setpaint (node ​​* node) {root = node; } Private: node * guardian; Std :: vector & lt; Node *> children; };  

Example:

  int main (int argc, char * argv []) {node parent; Node child; Parent.addChild (& amp; child); }  

Comments

Popular posts from this blog

java - Can't add JTree to JPanel of a JInternalFrame -

javascript - data.match(var) not working it seems -

javascript - How can I pause a jQuery .each() loop, while waiting for user input? -