问题
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