代码改变世界

多态(Polymorphism)

2016-07-24 17:19  金山大游侠  阅读(1005)  评论(0)    收藏  举报

C++里多态的概念有点乱,有时间上Wikipedia上搜索了下相关词条,总结如下:

 

Polymorphism(computer science)


在编程语言和类型理论中,Polymorphism(希腊语,意思为many shape)提供单个接口(single interface)给不同类型的实体(Polymorphism is the provision of a single interface to entities of different type.)。存在几种完全不同类型的多态。

1.Ad hoc polymorphism:函数能够依据参数类型指定不同的实现(depending on a limited range of individually specified types and combinations.)。

其实就是函数重载(function overloading)。包括运算符重载(operator overloading),因为运算符重载也是函数重载的一种

 

2.Parametric polymorphism:编码不指定任何特定类型,所以对任意数量的新类型来说是可以透明使用的(不需指定类型?)。在面向对象编程中,被称为generic programming(泛型编程),而在函数式编程中,则被简称为polymorphism。a function or a data type can be written generically so that it can handle values identically without depending on their type. Such functions and data types are called generic functions and generic datatypes respectively and form the basis of generic programming.

在C++里就是模板(template),编写的代码不指定类型,而是通过参数的类型推导出来。

 

3.Subtyping(also called subtype polymorphism or inclusion polymorphism):与公用超类关联的许多不同子类,同一个名字指定不同的实现(a name denotes instances of many different classes related by some common superclass. 翻译不一定准确?)。我的理解就是可以依据对象所属子类(派生于同一个超类)的不同,决定选择同名接口的不同实现。在面向对象编程中,常被简称为polymorphism。

在C++中就是虚函数(virtual function)。

 

多态可以分为静态和动态两种(static polymorphism, dynamic polymorphism),静态多态是编译期决定的(at compile time),动态多态是在运行时决定的(at run time)。通常,静态多态执行速度更快,也更易读和易于进行静态分析,但是需要编译器支持;而动态多态则更灵活,但是速度会慢一些,同时增加了理解难度。

 

静态多态代表性地出现在ad hoc polymorphism 和 parametric polymorphism中,而动态多态常用于 subtype polymorphism。

 

总结一下,所谓多态,就是指一个接口(interface)对应不同的类型实体。广义的多态,分为三种类型,分别是Ad hoc(同名函数,参数类型不同), Parametirc(编码不指定类型,编译时从参数推导出实际类型), Subtyping(子类从超类继承同名接口,实现不同的行为),分别对应C++中的function overloading, Template 和 virtual function。而C++中所谓的多态,对应的就是Subtyping,通过virtual function的方式来实现。对于C++来说,function overloading和template属于静态多态,在编译期决定;virtual function属于动态多态,在运行时决定。

 

参考链接:

1. https://en.wikipedia.org/wiki/Polymorphism_(computer_science)

2. https://en.wikipedia.org/wiki/Ad_hoc_polymorphism

3. https://en.wikipedia.org/wiki/Parametric_polymorphism

4. https://en.wikipedia.org/wiki/Subtyping