How to use virtual functions to achieve a polymorphic behavior in C++?

两盒软妹~` 提交于 2019-12-20 04:55:25

问题


I am new to these important features of C++, i have already read a few question/answers on these topics here and googled a few docs. But i am still confused with this...

It would be great if some one can advice me some good online tutorial or book chapter which takes this concepts easy and slow and starts it from the basic.

Also, if some one knows some on-hand exercise material that would be great.


回答1:


Here's the best explanation of polymorphism that I've ever heard:

There are many animals in this world. Most of them make some sound:

class Animal
{
public:
    virtual void throwAgainstWall() { };
};

class Cat : public Animal
{
public:
    void throwAgainstWall(){ cout << "MEOW!" << endl; }
};

class Cow : public Animal
{
public:
    void throwAgainstWall(){ cout << "MOOO!" << endl; }
};

Now imagine you have huge bag with animals and you can't see them. You just grab one of them and throw it against wall. Then you listen to its sound - that tells you what kind of animal it was:

set<Animal*> bagWithAnimals;
bagWithAnimals.insert(new Cat);
bagWithAnimals.insert(new Cow);

Animal* someAnimal = *(bagWithAnimals.begin());
someAnimal->throwAgainstWall();

someAnimal = *(bagWithAnimals.rbegin());
someAnimal->throwAgainstWall();

You grab first animal, throw it against wall, you hear "MEOW!" - Yeah, that was cat. Then you grab the next one, you throw it, you hear "MOOO!" - That was cow. That's polymorphism.

You should also check Polymorphism in c++

And if you are looking for good book, here is good list of 'em: The Definitive C++ Book Guide and List



来源:https://stackoverflow.com/questions/9260005/how-to-use-virtual-functions-to-achieve-a-polymorphic-behavior-in-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!