C++共享对象
我有四个类 A
、B
、C
和 D
。
- 类
A
有一个类的成员b
B
。 - 类
B
具有类C
的成员c
。
A
有一个成员 D* dpointer;
这个层次结构必须保留(事实上,这是一个 GUI,其中应用程序、窗口、面板为 A
、B
和 C
)。
现在 B 和 C 必须使用 *dpointer
中的方法。
还有什么比将 dpointer 作为 B
和 C
的成员更优雅的吗?是不是很糟糕?
I have got four classes A
, B
, C
and D
.
- Class
A
has a memberb
of classB
. - Class
B
has a memberc
of classC
.
A
has a member D* dpointer;
This hierarchy has to be preserved (in fact this is a GUI with app, window, panel as A
, B
and C
).
Now B and C must use a method from *dpointer
.
Is there something more elegant than giving dpointer
as a member of B
and C
? Is it bad ?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
在实践中,我可能会选择上面提到的shared_ptr解决方案。但这里有另一种在 C++ 文献中不常见的方法,您可能会在面试问题或 BrainBench 测试中找到这种方法:
私有继承实现 has-a 关系,就像使其成为成员一样。唯一的区别是每种类型只能拥有一种。在这种情况下,同一 D 对象由组合中的所有类共享。
但如果您希望其他人能够理解您在做什么,请使用shared_ptrs。
In practice, I would probably opt for the shared_ptr solution mentioned above. But here is another way that is not often covered in the C++ literature, of the sort you might find in an interview question or a BrainBench test:
private inheritance implements the has-a relationship, just like making it a member. The only difference is that you can only have one of each type. In this case the same D object is shared by all classes in the composition.
But if you want others to be able to understand what you are doing, go with the shared_ptrs.
不直接,但您可以将 D 放在
shared_ptr
中,这将减轻您可能遇到的内存管理问题。Not directly, but you could put D inside of a
shared_ptr<D>
, which would alleviate any memory management headaches you might possibly have.在这种情况下,您可能应该传递对
B
和C
的引用而不是指针。正如 @Billy ONeil 在 他的答案中所说,您应该使用shared_ptr
或scoped_ptr
如果可能且合适(无法判断不了解A
中的D
和dpointer
的更多信息)。传递对
B
和C
的引用的优点是清楚地表明这两个仅使用D
对象,但不控制它的生命周期,并且需要D
的实例才能使用这些类(带有指针NULL
将是一个选项)。如果B
和C
仅调用D
上的const
方法,您甚至可以传递 const 引用。In this situation you should probably pass a reference to
B
andC
instead of a pointer. As @Billy ONeil says in his answer, you should use ashared_ptr
or ascoped_ptr
if possible and appropriate (cannot judge without knowing more aboutD
anddpointer
) inA
.Passing a reference to
B
andC
has the advantage of making clear that these two merely usethe
D
-object, but do not control it's lifecycle, and that an instance ofD
is required to use these classes (with a pointerNULL
would be an option). IfB
andC
only callconst
methods onD
, you can even pass a const reference.