Relationships between objects
There are many different kinds of relationships two objects may have in real-life, and we use specific “relation type” words to describe these relationships. For example: a square “is-a” shape. A car “has-a” steering wheel. A computer programmer “uses-a” keyboard. A flower “depends-on” a bee for pollination. A student is a “member-of” a class. And your brain exists as “part-of” you (at least, we can reasonably assume so if you’ve gotten this far).
All of these relation types have useful analogies in C++.
In this chapter, we’ll explore the nuances of the relation types “part-of”, “has-a”, “uses-a”, “depends-on”, and “member-of”, and show how they can be useful in the context of C++ classes. We’ll also explore a couple of related topics that don’t fit nicely anywhere else.
Composition vs aggregation vs association summary
Here’s a summary table to help you remember the difference between composition, aggregation, and association:
| Property | Composition | Aggregation | Association |
|---|---|---|---|
| Relationship type | Whole/part | Whole/part | Otherwise unrelated |
| Members can belong to multiple classes | No | Yes | Yes |
| Members existence managed by class | Yes | No | No |
| Directionality | Unidirectional | Unidirectional | Unidirectional or bidirectional |
| Relationship verb | Part-of | Has-a | Uses-a |
本文探讨了C++中对象间的关系类型,包括“part-of”(组成部分)、“has-a”(拥有)、“uses-a”(使用)、“depends-on”(依赖于)和“member-of”(成员)。通过实例说明了这些关系如何映射到现实生活中的概念,并讨论了它们在C++类设计中的应用。
3000

被折叠的 条评论
为什么被折叠?



