1. 继承-inheritance
表达了实现的复用。
inheritance
是从代码复用角度提出的概念,和类型没有直接联系。
2. 子类型-subtyping
在编程语言理论中,子类型subtypeing
(也称为子类型多态性subtype polymorphism
,包含多态inclusion polymorphism
)是类型多态性的一种形式。
通常表达A是B的子类型,则在使用B的场合都可以替换为使用A。
3. inheritance
与subtyping
区别
inheritance
表达了实现间的关系。
subtyping
表达了类型间的关系。
Subtyping should not be confused with the notion of (class or object) inheritance from object-oriented languages;[1] subtyping is a relation between types (interfaces in object-oriented parlance) whereas inheritance is a relation between implementations stemming from a language feature that allows new objects to be created from existing ones.
4. 多态
C++多态分为两类:静态多态、动态多态。
静态多态
静态多态也称为静态绑定或早期绑定,编译器在编译期间完成, 编译器根据函数实参的类型(可能会进行隐式类型转换) , 推断出要调用哪个函数, 如果有对应的函数就调用该函数, 否则出现编译错误。
泛型编程
,函数重载
可以实现静态多态。
当编译器对一个函数调用选择其合适的实现时,优先级从高到低依次为:
- 普通函数
- 基础模板
- 特化模板
普通函数相对于模板函数要更有弹性:普通函数支持类型的自动转化;但模板函数则更刻板,不能发现类型之间的自动转换关系。
动态多态。
在程序执行期间(非编译期)根据实际对象判断调用对应的方法。
C++通过虚函数
实现动态多态。
鸭子类型 Duck Typing
When I see a bird that walks like a duck and swims like a duck and quacks like a duck, I call that bird a duck. @Wikipeida
C++模板
C++使用模板来实现Duck Typing
Go interface
- 一个类型不需要显式地声明它实现了某个接口
- 但仅当某个变量的类型实现了某个接口的
所有
方法,这个变量才能用在要求这个接口的地方。
网友评论