C++ “has-a”和“is-a”是什么意思?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9677545/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 13:09:52  来源:igfitidea点击:

What do "has-a" and "is-a" mean?

c++oop

提问by kovenzhang

Can anyone explain what "HAS-A" and "IS-A" means between two class.

谁能解释一下两个班级之间“HAS-A”和“IS-A”的含义。

An example would helpful.

一个例子会有所帮助。

回答by paxdiablo

In the object-oriented world, a class can besomething or it can containsomething.

在面向对象的世界中,类可以某些东西,也可以包含某些东西。

For example, a Queueclass may bea sub-class of a LinkedListclass (since a linked list can certainly be used to implement a queue). That is an is-arelationship. Everything that you can do to the linked list, you should be able to do to the queue.

例如,一个Queue类可能一个类的子LinkedList类(因为链表当然可以用来实现一个队列)。那是一种is-a关系。您可以对链表执行的所有操作,都应该可以对队列执行。

However, the queue class may also hold otherinformation such as the number of items in the linked list (for efficiency).

然而,队列类也可能保存其他信息,例如链表中的项目数(为了效率)。

To that end, it may also define a member variable called size. That would be a has-arelationship - the queue is not a subclass of the integer, it simply contains an integer.

为此,它还可以定义一个名为 的成员变量size。这将是一种has-a关系 - 队列不是整数的子类,它只包含一个整数。

回答by Martin York

  • A car is-a vehicle
  • A car has-a steering wheel
  • 汽车是一辆车
  • 汽车有方向盘

Eg:

例如:

class SteeringWheel
{};

class Vehicle
{
    virtual void doStuff() = 0;
};

class Car: public Vehicle
{
    SteeringWheel  sWheel;
    virtual void doStuff();
};

回答by Michael Dillon

These are two common forms of relationship between two classes.

这是两个类之间的两种常见关系形式。

The HAS-A relationship refers to a class X which has a class Y as a component, probably expressed by placing an instance of class Y as an attribute in every object of class X.

HAS-A 关系是指一个类 X,它有一个类 Y 作为组件,可能通过将类 Y 的实例作为属性放置在类 X 的每个对象中来表示。

The IS-A relationship refers to a class W which is a class Z, probably because class W is a subclass of class Z, or has class Z somewhere in its inheritance graph. Code which knows how to deal with instances of class Z should be able to handle instances of class W with no code changes required.

IS-A 关系指的是类 W,它是类 Z,可能是因为类 W 是类 Z 的子类,或者在其继承图中的某处有类 Z。知道如何处理 Z 类实例的代码应该能够处理 W 类实例而无需更改代码。