一、多态
1、 概念:同一事物表现出的多种形态,同一操作作用于不同的对象,可以有不同的解释,产生不同的执行结果。在运行时,可以通过指向基类的指针,来调用实现派生类中的方法。
2、 举例子:
#include<windows.h>
class WashRoom
{
public:
void GoToManWashRoom()
{
cout << "Man ---> Please Left" << endl;
}
void GoToWomanWashRoom()
{
cout << "Woman ------> Please Right" << endl;
}
};
class Person
{
public:
virtual void GoToWashRoom(WashRoom& wc) = 0;
};
class Man :public Person
{
public:
virtual void GoToWashRoom(WashRoom& wc)
{
wc.GoToManWashRoom();
}
};
class Woman :public Person
{
public:
virtual void GoToWashRoom(WashRoom& wc)
{
wc.GoToWomanWashRoom();
}
};
void TestWashRoom()
{
WashRoom wc;
Person* p = NULL;
for (int i = 0; i <10; ++i)
{
if ((rand()) & 0x01)
p = new Man;
else
p = new Woman;
p->GoToWashRoom(wc);
delete p;
Sleep(1000);
}
}
int main()
{
TestWashRoom();
return 0;
}
3、 多态的分类
(1)静态多态:编译器在编译期间来确定程序的行为(确定具体调用哪个函数)
A:函数重载
B:泛型编程
(2)动态多态:程序运行时来确定程序的行为(确定具体调用哪个函数)
4、 动态多态实现条件
(1) 基类中必须包含虚函数,在派生类中必须对基类的虚函数进行重写
(2) 必须通过基类指针或引用调用虚函数