C + + polymorphic

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.