多态的概念
1. What is Polymorphism?
1.1. 广义的多态:不同类型的实体/对象对于同一消息有不同的响应,就是OOP中的多态性。
1.2. 截止目前:多态性有两种表现的方式
1.2.1. 重载多态:
class C
{
public:
int f(int x);
int f( );
};
1.2.2. 子类型多态:不同的对象调用同名重定义函数,表现出不同的行为
class A { virtual int f() {return 1;} };
class B: public A { virtual int f() {return 8;} };
A a; B b;
A* p = &b;
a.f() // call A::f()
b.f() // call B::f()
p->f(); // call B::f()
2. Binding
2.1. 联编(Binding): 确定具有多态性的语句调用哪个函数的过程。
2.2. 静态联编
在程序编译时(Compile-time)确定调用哪个函数
例:函数重载
2.3. Dynamic Binding (动态联编)
在程序运行时(Run-time),才能够确定调用哪个函数
用动态联编实现的多态,也称为运行时多态(Run-time Polymorphism)。
实现运行时多态
1. 为何要使用运行时多态?
print()调用toString()输出信息,需要分别写三个重载函数,才能实现多态输出
void print( A obj );
void print( B obj );
void print( C obj );