什么是"is-implemented-in-terms-of"关系,何时应使用它?

What is the "is-implemented-in-terms-of" relationship, and when should I use it?

本文关键字:何时应 is-implemented-in-terms-of 关系 什么      更新时间:2023-10-16

我了解到在OOP中我们可以使用继承,这样我们就可以从基类中派生类。我们称这种关系为"is - a关系",例如:一个人是从阶级人类派生出来的。

也有包含,这意味着一个类包含另一个类类型的对象,所以我们可以说一辆车有轮子。我们称之为"哈斯- a关系"。

还有另一种关系叫做"is - implementation - in - terms - of",我不确定我是否理解它。这意味着私有继承吗?

#include <iostream>
using namespace std;
class A {
};
class B : public A {
}; // is-a relationship
class C {
    A& aObj;
}; // C has-a relationship
// is implemented in terms of?? and how and when?
int main()
{
    A a;
    B b; // b is a an A like man is-a human
    C c; // c contains an A's object so C has-a an A's part
    cout << endl;
    return 0;
}

c++中的私有继承有时用来表示"按…实现"的关系。如果A私有地继承了B,这意味着A在内部拥有B的所有状态和行为,并且可以在自己的实现中使用这些行为。

在许多情况下,最好使用复合来完成此操作(只需让A拥有B类型的私有数据成员,而不是私有继承),但它仍然偶尔会发现一些用途。在c++ 11中删除函数语法之前,它经常被用来创建不允许复制行为的类,在某些情况下,如果有问题的对象是空的,它被用来节省空间。不过,一般来说,只使用合成。这样更容易,更干净,更不容易让人混淆。