PKU C + + programming Practice Learning Note 3 polymorphism and virtual functions

Source: Internet
Author: User

The sixth chapter polymorphism and virtual function

6.1 Basic concepts of polymorphism and virtual functions Introduction

Polymorphism is a very important mechanism in object-oriented programming. It can effectively improve the scalability of the program.

Some programming languages have the concept of being inherited by objects, but without the notion of polymorphism, such programming languages can only be called object-based programming languages, not object-oriented languages, such as Visual Basic.

Virtual functions

In the definition of a class, a member function preceded by the virtual keyword is a virtual function.

Class Base {  <span style= "color: #ff0000;" >virtual</span> int get ();}; int Base::get () {}
The virtual keyword is used only in function declarations in the class definition, not when writing a function body.

Constructors and static member functions cannot be virtual functions.

The essential difference between virtual functions and ordinary functions is that virtual functions can participate in polymorphism, while ordinary member functions cannot.


Polymorphism has two forms of expression

Polymorphic representation One, a pointer to a base-class pointer-derived class can be assigned to a base-class pointer. (Assignment compatibility rule)

When calling a virtual function with the same name in a base class and derived class through a base-class pointer:
(1) If the pointer points to an object of a base class, then the call is a virtual function of the base class;
(2) If the pointer points to an object of a derived class, the virtual function of the derived class is called.

This mechanism is called "polymorphic".

Example

Class CBase {public  :    virtual void somevirtualfunction () {}};class cderived:public CBase {public  :    virtual void Somevirtualfunction () {}};int main () {  cderived oderived;  CBase * p = & oderived;  P--somevirtualfunction (); Which virtual function is called depends on <span style= "color: #ff0000;" What type of object >p points to, not P's pointer type </span>  return 0;}
At compile time there is no way to determine which class the somevirtualfunction of this statement calls.

Polymorphic representation Two, base class reference

An object of a derived class can be assigned to a base class reference

When calling a virtual function with the same name in a base class and derived class through a base class reference:
(1) If the reference refers to a base class object, then the call is the virtual function of the base class;
(2) If the reference refers to an object of a derived class, then the virtual function of the derived class is called.

This mechanism is also called "polymorphic".

Example

Class CBase {public  :    virtual void somevirtualfunction () {}};class cderived:public CBase {public  :    virtual void Somevirtualfunction () {}};int main () {  cderived oderived;  CBase & r = oderived;  R.somevirtualfunction (); Which virtual function is called depends on <span style= "color: #ff0000;" >r refers to which type of object, not R's reference type </span>  

A simple example of polymorphism

Class A {public  :    virtual void Print ()    {cout << "A::P rint" <<ENDL;}; Class B:public A {public  :    virtual void Print () {cout << "B::P rint" <<endl;}}; Class D:public A {public  :    virtual void Print () {cout << "D::P rint" << Endl;}}; Class E:public B {  virtual void Print () {cout << "E::P rint" << Endl;}};
int main () {  a A; b b; e e; D D;  A * PA = &a; B * PB = &b;  D * pd = &D; E * pe = &e;  Pa->print (); A.print () is called, Output: A::P rint  pa = PB;  PA-and Print (); B.print () is called, Output: B::P rint  pa = pd;  PA-and Print (); D. Print () is called, output: D::P rint  pa = pe;  PA-and Print (); E.print () is called, Output: E::P rint  return 0;}

Polymorphism is used in object-oriented program design to enhance program Scalability, that is, when the program needs to modify or add functionality, the code needs to be changed and added less.


6.2 Using Polymorphic Game program instances Game "Heroes of the Magic Gate Invincible"

There are many kinds of monsters in the game, each of which has a class corresponding to it, and each monster is an object. Class: Cdragon, Class: Csoldier, Class Cphonex, class: Cangel
Monsters can attack each other, attack enemies and be attacked with corresponding actions, which are implemented through the object's member functions.
When the game version is upgraded, add a new monster-Thunderbird. How do you program to make code churn and increase less during upgrade? New class: Cthunderbird

Basic ideas:

Write Attack, fightback, and hurted member functions for each monster class.

    • The Attact function acts as an attack, attacks a monster, and invokes the hurted function of the attacked monster to reduce the health of the attacked monster while also invoking the fightback member function of the attacked monster, which is countered by the attacking monster.
    • The hurted function reduces its own health and acts as an injury.
    • The fightback member function acts as a counterattack action and invokes the Hurted member function of the object being countered, causing the object to be injured.
Sets the base class Ccreature, and causes other classes, such as Cdragon, Cwolf, to derive from Ccreature.
A method of non-polymorphic implementation
Class class Ccreature {  protected:     int npower;//for attack    int nlifevalue;//Health value};class cdragon:public ccreat ure {public  :    void Attack (Cwolf * pwolf) {      ... Code      pwolf->hurted (npower) that shows the attack action;      Pwolf->fightback (this);    }    void Attack (Cghost * pGhost) {      ... Code      pghost->hurted (npower) that shows the attack action;      Pgohst->fightback (this);    }    void hurted (int npower) {      .... Code Nlifevalue-= npower to perform the injured action      ;    void Fightback (Cwolf * pwolf) {      .... The Code      pwolf->hurted (NPOWER/2) showing the counterattack action    ;    void Fightback (Cghost * pGhost) {      .... Code    pghost->hurted (NPOWER/2) showing the counterattack action;  }}
There are n kinds of monsters, there will be N Attack member functions in the Cdragon class, and N fightback member functions. This is true for other classes as well.

Disadvantages of non-polymorphic implementations if the game version is upgraded, adding a new monster Thunderbird Cthunderbird, then the program changes larger. All classes require an additional two member function: void Attack (Cthunderbird * pthunderbird); void Fightback (Cthunderbird * pthunderbird); when there are many kinds of monsters, the workload is bigger and there is wood!!!

Multi-State Implementation method
Base class Ccreature:class Ccreature {  protected:    int m_nlifevalue, m_npower;  Public:    virtual void Attack (Ccreature * pcreature) {}    virtual void hurted (int npower) {}    virtual void fight Back (Ccreature * pcreature) {}};
The base class has only one Attack member function, and there is only one fightback member function, and so is the derived class for all ccreature.
Derived class Cdragon:class Cdragon:public ccreature {public  :    virtual void Attack (Ccreature * pcreature);    virtual void hurted (int npower);    virtual void fightback (Ccreature * pcreature);}; void Cdragon::attack (Ccreature * p) {  ... Code p->hurted (M_npower) that shows the attack action,   //polymorphic  P->fightback (this),//polymorphic}void cdragon::hurted (int npower) {  ..... Code m_nlifevalue-= npower that shows the injury action  ; void Cdragon::fightback (Ccreature * p) {  ... Code that shows the counterattack action   
The advantages of a polymorphic implementation method if the game version is upgraded, add the new monster Thunderbird Cthunderbird ... You just need to write a new class Cthunderbird, and you don't need to add to the new monsters in the existing classes:
void Attack (Cthunderbird * pthunderbird);
void Fightback (Cthunderbird * pthunderbird);
member functions,Existing classes can be left intact, no pressure AH!!!

Principle
According to polymorphic rules, the above (1), (2), (3) are entered into the Cdragon::attack function and can be called separately:
cwolf::hurted
cghost::hurted
cbird::hurted
void Cdragon::attack (<span style= "color: #3333ff;" >ccreature * p</span>) {  p->hurted (m_npower);//polymorphic  

6.3 More Polymorphic Program instances Geometry Handler program: Enter parameters for several geometric shapes, which require an area-ordered output. Specify the shape when outputting.
Input:
The first line is the number of geometries N (no more than 100). There are n lines below, with each line beginning with a letter C.
If C is ' R ', it represents a rectangle, followed by two integers, respectively, the width and height of the rectangle;
If C is ' C ', it represents a circle, and the bank follows an integer representing its radius;
If C is ' T ', it represents a triangle, followed by three integers representing the length of three edges.
Output:
The type and area of each geometric shape are output by area from small to large. Each line is a geometric shape with the output format:
Body Name: Area

PKU C + + programming Practice Learning Note 3 polymorphism and virtual functions

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.