多态,静态多态和动态多态
多态的定义
多态按字面的意思就是多种形态。当类之间存在层次结构,并且类之间是通过继承关联时,就会用到多态。
C++ 多态意味着调用成员函数时,会根据调用函数的对象的类型来执行不同的函数。
多态性:调用同一个函数名,但可以根据需要实 现不同的功能。(消息相同,响应不同)

运行时的多态性是指在程序执行之前,根据函数名和 参数无法确定应该调用哪一个函数,必须在程序的执 行过程中,根据具体的执行情况来动态地确定
静态多态(函数重载)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
|
#include <iostream>
using namespace std;
class Shape {
protected:
int width, height;
public:
Shape( int a=0, int b=0)
{
width = a;
height = b;
}
int area()
{
cout << "Parent class area :" <<endl;
return 0;
}
};
class Rectangle: public Shape{
public:
Rectangle( int a=0, int b=0):Shape(a, b) { }
int area ()
{
cout << "Rectangle class area :" <<endl;
return (width * height);
}
};
class Triangle: public Shape{
public:
Triangle( int a=0, int b=0):Shape(a, b) { }
int area ()
{
cout << "Triangle class area :" <<endl;
return (width * height / 2);
}
};
// 程序的主函数
int main( )
{
Shape *shape;
Rectangle rec(10,7);
Triangle tri(10,5);// 存储矩形的地址
shape = &rec;// 调用矩形的求面积函数 area
shape->area();// 存储三角形的地址
shape = &tri;// 调用三角形的求面积函数 area
shape->area();
return 0;
}
|
输出结果
1
2
|
Parent class area :
Parent class area :
|
调用函数 area() 被编译器设置为基类中的版本,这就是所谓的静态多态,或静态链接 - 函数调用在程序执行前就准备好了。有时候这也被称为早绑定,因为 area() 函数在程序编译期间就已经设置好了。
动态多态
在 Shape 类中,area() 的声明前放置关键字 virtual
虚函数 是在基类中使用关键字 virtual 声明的函数。在派生类中重新定义基类中定义的虚函数时,会告诉编译器不要静态链接到该函数。
我们想要的是在程序中任意点可以根据所调用的对象类型来选择调用的函数,这种操作被称为动态链接,或后期绑定。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
|
class Shape {
protected:
int width, height;
public:
Shape( int a=0, int b=0)
{
width = a;
height = b;
}
virtual int area()
{
cout << "Parent class area :" <<endl;
return 0;
}
};
|
输出结果
1
2
|
Rectangle class area :
Triangle class area :
|
若要基类指针访问派生类中相同名字的函数,必须将基类中的同名函数定义为虚函数, 这样,将不同的派生类对象的地址赋给基类的指针变量后,就可以动态地根据这种赋值语句 调用不同类中的函数(动态绑定、动态关联)
动态多态实现注意事项
可以将一个派生类对象的地址赋给基类的指针变量
基类指针,只能引用从基类继承来的成员
使用基类的指针时,只能访问从相应基类中继承来的成员,而 不允许访问在派生类中增加的成员