什么是多态性,它的用途是什么,如何使用它?


当前回答

多态性是一种将对象类视为父类的能力。

例如,假设有一个类叫Animal,还有一个类叫Dog,它继承自Animal。多态性是将任何Dog对象视为Animal对象的能力,如下所示:

Dog* dog = new Dog;
Animal* animal = dog;

其他回答

在面向对象语言中,多态性允许通过同一个接口处理和处理不同的数据类型。例如,考虑c++中的继承: 类B派生自类A。类型为A*的指针(指向类A的指针)可以用来处理类A的对象和类B的对象。

我知道这是一个有很多好答案的老问题,但我想用一句话来回答:

将派生类型视为其基类型。

上面有很多例子可以说明这一点,但我觉得这是一个很好的简明答案。

一般来说,它是一种使用相同或表面上相似的API来为许多不同类型的对象提供接口的能力。有多种形式:

Function overloading: defining multiple functions with the same name and different parameter types, such as sqrt(float), sqrt(double) and sqrt(complex). In most languages that allow this, the compiler will automatically select the correct one for the type of argument being passed into it, thus this is compile-time polymorphism. Virtual methods in OOP: a method of a class can have various implementations tailored to the specifics of its subclasses; each of these is said to override the implementation given in the base class. Given an object that may be of the base class or any of its subclasses, the correct implementation is selected on the fly, thus this is run-time polymorphism. Templates: a feature of some OO languages whereby a function, class, etc. can be parameterised by a type. For example, you can define a generic "list" template class, and then instantiate it as "list of integers", "list of strings", maybe even "list of lists of strings" or the like. Generally, you write the code once for a data structure of arbitrary element type, and the compiler generates versions of it for the various element types.

多态性字面上的意思是多种形状。(或多种形式): 对象来自不同的类和同名方法,但工作流不同。 一个简单的例子是:

假设一个人X。

他只是一个人,但他的行为却像许多人一样。 你可能会问:

他是他母亲的儿子。 朋友对朋友。 兄弟之于姐妹。

我为另一个问题提供了多态性的高级概述:

c++中的多态性

希望能有所帮助。一个提取…

...从简单的测试和[多态性]定义开始会有所帮助。考虑下面的代码:

Type1 x;
Type2 y;

f(x);
f(y);

这里,f()是执行一些操作,并被赋予值x和y作为输入。要具有多态性,f()必须能够操作至少两种不同类型的值(例如int和double),查找并执行适合类型的代码。

(继续在Polymorphism in c++)