一. 多态的概念
同一事物,在不同场景下的多种形态
例如:“*”在不同场景下的形态
int* p=&a
*p
a*b
二.多态的分类
1.静态多态:编译器在编译期间完成的,编译器根据函数实参的类型(可能会进行隐式类型转换),可推断出要调用那个函数,如果有对应的函数就调用该函数,否则出现编译错误。
int Add(int a,int b)
{
return a+b;
}
float Add(int a,int b)
return a+b;
}
int main()
{
cout<<Add(10,20)<<end1;
cout<<Add(3.14f,5.6f)<<end1;
return 0;
}
2.动态多态:在程序执行期间(非编译期)判断所引用对象的实际类型,根据其实际类型调用相应的方法。
class WashRoom
{
public: void GoToManWashRoom()
{
cout << "Man-->Please Left" << endl;
}
void GoToWomanWashRoom()
{
cout << "Woman-->Please Right" << endl;
}
};
class Person
{
public: virtual void GoToWashRoom(CWashRoom & _washRoom) = 0;
};
class Man :public Person
{
public: virtual void GoToWashRoom(WashRoom & washRoom)
{
washRoom.GoToManWashRoom();
}
};
};
class Woman :public Person
{
public:
virtual void GoToWashRoom(WashRoom & washRoom)
{
washRoom.GoToWomanWashRoom();
}
};
void FunTest()
{
WashRoom washRoom;
for (int iIdx = 1; iIdx <= 10; ++iIdx)
{
Person* pPerson;
int iPerson = rand() % iIdx;
if (iPerson & 0x01)
pPerson = new Man;
else
pPerson = new Woman;
pPerson->GoToWashRoom(washRoom);
delete pPerson;
pPerson = NULL;
Sleep(1000);
}
三. 动态多态的实现条件
1.基类中必须有虚函数;
class Base
{
public:
virtual void FunTest1(int _iTest){ cout << "Base::FunTest1()" << endl; }
void FunTest2(int _iTest){ cout << "Base::FunTest2()" << endl; }
virtual void FunTest3(int _iTest1){ cout << "Base::FunTest3()" << endl; }
virtual void FunTest4(int _iTest){ cout << "Base::FunTest4()" << endl; }
};
class Derived :public Base
{
public:
virtual void FunTest1(int _iTest){ cout << "Derived::FunTest1()" << endl; }
virtual void FunTest2(int _iTest){ cout << "Derived::FunTest2()" << endl; }
void FunTest3(int _iTest1){ cout << "Derived::FunTest3()" << endl; }
virtual void FunTest4(int _iTest1, int _iTest2)
virtual void FunTest4(int _iTest1, int _iTest2)
{
cout << "Derived::FunTest4()" << endl;
}
};
int main()
{
Base* pBase = new Derived;
pBase->FunTest1(0);
pBase->FunTest2(0);
pBase->FunTest3(0);
pBase->FunTest4(0);
pBase->FunTest4(0, 0);
return 0;
}
2.通过基类类型的引用或者指针调用虚函数;
四.多态的实现原理
a、编译时多态性(静态多态):通过重载函数实现
b、运行时多态性(动态多态):通过虚函数实现。