Is it bad practice for a child object to have a pointer to its parent?

前端 未结 7 1761
我寻月下人不归
我寻月下人不归 2020-12-20 12:27

In a C++ application, let\'s say I have a window class, which has several instances of a control class. If my window wanted to notify a control that it had been clicked, I m

7条回答
  •  悲哀的现实
    2020-12-20 13:12

    It is OK. However, make sure you need it because it can complicate your code in situations where a childs parent can change. Examine why the child needs to know who its parent is and consider the costs and alternatives. An example alternative for your scenario would be: Resizing can come from the top down when a parents window is resized it can tell its children to resize by iterating and calling a method or setting a property. When a child needs to resize (like a textbox that can grow based on the data in it) it can raise an event to anyone listening saying that it resized and the parent could listen for that event.

提交回复
热议问题