简体   繁体   English

我认为将继承视为这三件事的组合是否正确?

[英]Am I correct to think of inheritance as a combination of these 3 things?

A inherits B means A继承B意味着

  1. A owns B. A拥有B.
  2. A shares all B interface. A共享所有B接口。
  3. A shares implementation of B interface. A股实现B接口。

Abstract classes are similar (@protocol in objective-c, for example. 抽象类是相似的(例如,在objective-c中的@protocol)。

A implements B means 2. A shares all B interface. A实现B意味着2.A共享所有B接口。

As for A owns B and A shares implementation of B, I see that as something that can be "pushed" with combination of @protocol and category. 至于A拥有B和A共享B的实现,我认为可以通过@protocol和类别的组合来“推动”。

In any case, that's all inheritance is all about right? 无论如何,这一切都是正确的吗?

  1. Ownership 所有权
  2. Sharing interface 共享界面
  3. Sharing implementation. 分享实施。

If I am wrong in any of these, would anyone please correct me. 如果我在其中任何一个错了,请有人纠正我。

Ownership 所有权

Yes, that's essentially correct. 是的,这基本上是正确的。 Some might quibble about the "ownership" claim. 有些人可能会对“所有权”主张提出质疑。 That might suggest that B "has a" A rather than B "is an" A. In object-oriented lingo, a has-a relationship generally implies that one of B's fields is a pointer to an A object. 这可能表明B“有一个A而不是B”是一个“A.在面向对象的术语中,一个有一个关系通常意味着B的一个字段是指向A对象的指针。 An is-a relationship implies that part of B's memory contains an A object. is-a关系意味着B的内存的一部分包含A对象。 With common object-oriented languages, inheritance implies an is-a relationship, not a has-a relationship. 对于常见的面向对象语言,继承意味着is-a关系,而不是has-a关系。

Consider these two sketches 考虑这两个草图

B has-a A
=========

        +--------------+    +----------------+
B* b -> | A* a_part    | -> | float a_field1 |
        | int b_field1 |    | float a_field2 |
        | int b_field2 |    +----------------+
        +--------------+

B is-a A
========

        +----------------+
B* b -> | float a_field1 | <- A* a_part_of_b
        | float a_field2 |
        | int   b_field1 |
        | int   b_field2 |
        +----------------+

Another important property of an is-a relationship is that a pointer to the subclass can be safely treated as a pointer to the superclass. is-a关系的另一个重要属性是指向子类的指针可以被安全地视为指向超类的指针。 This doesn't normally work with has-a relationships without a conversion or extraction method being employed. 这通常不适用于没有采用转换或提取方法的has-a关系。

The concept of 'ownership' here is maybe problematic. 这里的“所有权”概念可能存在问题。 I think the most simple way to put it is that 'A', when inheriting from 'B', does everything that 'B' does, except for when 'A' decides to do something different. 我认为最简单的方法就是'A',当继承自'B'时,做'B'所做的一切,除了'A'决定做一些不同的事情。 'A' has no ownership of 'B', other than that by default it acts as 'B' until you tell it to do something different. 'A'没有'B'的所有权,除了默认情况下它会充当'B',直到你告诉它做一些不同的事情。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM