Polymorphic 1. polymorphic use
The interface does not need to be modified in order for the code to be reused easily and to add a feature.
#include <iostream>using namespace std;class A{public: virtual void eat(){} virtual void sleep(){}};class Human : public A{public: void eat(){ cout << "Human eat" << endl; } void sleep(){ cout << "Human sleep" << endl; }};class Pig : public A{public: void eat(){ cout << "Pig eat" << endl; } void sleep(){ cout << "Pig sleep" << endl; }};//这个fun方法是个对外的接口,当需要增加新功能时,新的功能只需要继承class A,就可以使用这个接口。void fun(A& a){ a.eat(); a.sleep();}int main(){ Human h; Pig p; fun(h);//调用的是Human的eat和sleep fun(p);//调用的是Pig的eat和sleep}
2. Conditions necessary for polymorphic formation
- Virtual functions
- Method with the same name
- Method parameter numbers are the same, method parameters are of the same type
- Return value type is the same
- You must use a pointer or reference from the parent class, and the object of the parent class cannot form a polymorphic
However, there is one exception, although the return value type is different, but the return value of the parent class's method is a pointer to the parent class, and the return value of the method of the subclass is a pointer to the subclass, and can also form polymorphism.
#include <iostream>using namespace std;class Base{public: virtual Base* show(){ cout << "Base show" << endl; }};class D : public Base{ D* show(){//返回值和父类不一样,但因为是父子关系,所以也可以形成多态 cout << "D show" << endl; }};int main(){ D d; Base* pb = &d; pb->show();//调用的是子类的show方法}
C + + polymorphic