C ++ virtual functions parse

In C ++ , the former members of the base class function declaration with the keyword virtual to allow this function to be virtual function , this function of the derived class will inherit different implementations of this modifier, allowing subsequent coverage derived class, to late binding effect. Even the base class member function calls the virtual function, also called the derived class version

 

For example, a base class has a virtual function Animal eat. Subclass Fish appear to be real to be a function eat (), this subclass Fish and subclasses Wolf is completely different, but you can refer to function under the category Animal eat () definition and use of sub-categories under the Fish function eat () of process.

C++

The following code is an example of C ++ program. It should be noted that this example does not code for exception handling. Especially new or vector :: push_back throw an exception, the program is possible runtime crash or error phenomenon.

#include <iostream>
#include <vector>using namespace std;
class Animal{
public:    virtual void eat() 
const { cout << "I eat like a generic Animal." << endl; }    
virtual ~Animal() {}
}; 

class Wolf : public Animal{
public:    
void eat() 
const { cout << "I eat like a wolf!" << endl; }}; class Fish : public Animal{public:    void eat() const { cout << "I eat like a fish!" << endl; }}; class GoldFish : public Fish{public:    void eat() const { cout << "I eat like a goldfish!" << endl; }};  class OtherAnimal : public Animal{}; int main(){    std::vector<Animal*> animals;    animals.push_back( new Animal() );    animals.push_back( new Wolf() );    animals.push_back( new Fish() );    animals.push_back( new GoldFish() );    animals.push_back( new OtherAnimal() );     for( std::vector<Animal*>::const_iterator it = animals.begin();       it != animals.end(); ++it)     {        (*it)->eat();        delete *it;    }    return 0;}

The following is a virtual function Animal :: eat () output:

1

I eat like a generic Animal.I eat like a wolf!I eat like a fish!I eat like a goldfish!I eat like a generic Animal.

When Animal :: eat () virtual function declared not to be output as follows:

1

I eat like a generic Animal.I eat like a generic Animal.I eat like a generic Animal.I eat like a generic Animal.I eat like a generic Animal.

 

Published 352 original articles · won praise 115 · views 130 000 +

Guess you like

Origin blog.csdn.net/Aidam_Bo/article/details/105218344