子对象有一个指向其父对象的指针是不好的做法吗? [英] Is it bad practice for a child object to have a pointer to its parent?

查看:185
本文介绍了子对象有一个指向其父对象的指针是不好的做法吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在C ++应用程序中,假设我有一个窗口类,它有几个控件类的实例。如果我的窗口想通知控件它已被点击,我可以使用:

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 might use:

control[n]->onClick();

现在让我们假设控件需要知道它的父窗口的大小,或者其他一些信息。为此,我考虑给控件一个指针本身(this)作为其构造函数的参数。然后我将通过控件onClick()方法进行调用:

Now let's say that the control needs to know the size of it's parent window, or some other information. For this I was considering giving the control a pointer to itself (this) as a parameter to it's constructor. I would then make a call like this from the controls onClick() method:

Size windowsize = parent->getSize();

这会被认为是不好的做法,还是以任何其他方式违背面向对象编程的价值?如果是这样,他这样做的正确方法是什么?

Would this be considered bad practice, or in any other way contradict the values of object orientated programming? If so, what would he the 'proper' way of doing this?

作为一个问题,最好有一个类或类*的向量?是否值得增加的速度增益的复杂性? (向量的更改很少见)。

As a side question, would it be better to have a vector of Class or Class*? Is it worth the added complexity for the speed gain? (Changes to the vector would be infrequent).

推荐答案

您可以将控件的层次结构视为树状图形数据结构体;当你以这种方式进行可视化时,控件有一个指向其父对象的指针是相当合理的。

You can consider a hierarchy of controls as being a tree-like graph data structure; when you visualize it that way, it's quite reasonable for a control to have a pointer to its parent.

对于对象或对象的指针是否应该存储在向量中,好,这取决于。你通常喜欢存储对象,但是有很多次你不能这样做,或者这是不切实际的。例如,如果你需要利用多态性并存储不同类型的东西,这些东西都是从一个共同的基类派生的,你需要使用指针。

As for whether objects or pointers to objects should be stored in a vector, well, it depends. You should usually prefer to store objects, but there are a lot of times that you can't do so or it's impractical to do so. For example, if you need to take advantage of polymorphism and store different types of things all derived from a common base class, you'll need to use pointers.

如果你做存储指针,确保使用某种智能指针或指针容器;否则,异常安全是一个跳动。

If you do store pointers, make sure to either use a smart pointer of some kind or a pointer container; otherwise, exception safety is a beating.

这篇关于子对象有一个指向其父对象的指针是不好的做法吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆