c++多态分为两种:
1.静态多态(静态绑定): 绑定发生在编译期.
如函数重载--------两个函数名称一样,参数类型或个数不完全相同,函数的返回类型可以不一样.
2.动态多态(动态绑定): 绑定发生在运行期.
动多态则是通过继承、虚函数(virtual)、指针(应用)来实现.
例子1.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
class A
{
public:
virtual A* Create();
};
A* A::Create()
{
printf("Parent Called\n");
return NULL;
}
class B: public A
{
public:
virtual B* Create();
};
B* B::Create()
{
printf("Child Called\n");
return NULL;
}
int main()
{
B b;
A& a = b;
a.Create();//输出 Child Called ------多态调用函数时和父子类中函数的返回类型没有多少关系.和函数名和参数(个数、类型)相关.
return 0;
}
例子2.
#include <stdio.h>
struct Point
{
int x;
int y;
void DebugPrint()
{
printf("[x, y] = [%d, %d]\n", x, y);
}
};
class A
{
public:
virtual Point* GetPoint();
virtual void Init();
};
void A::Init()
{
Point* point = GetPoint();
point->DebugPrint();
}
Point* A::GetPoint()
{
printf("Parent A.\n");
return NULL;
}
class B: public A
{
public:
B(int x, int y);
~B();
Point* GetPoint();
protected:
Point point;
};
Point* B::GetPoint()
{
printf("Child B.\n");
return &point;
}
B::B(int x, int y)
{
point.x = x;
point.y = y;
}
B::~B()
{}
int main()
{
B b(10, 9);
A& a = b;
a.Init();//里面调用的是B::GetPoint(),这也是一种多态的使用.
return 0;
}
说明:
1.含有虚函数的类的对象的数据区的开始位置存放的是一个指向虚表的指针,当出现一个父类指针(或引用)指向子类对象,然后通过父类指针或是引用调用子类函数时回去查虚表中有没有被调用函数,如果有则调用(子类中的),没有则会调用父类的。
2.父类中的虚函数必须要实现,不能只有声明。