如何使用虚函数在 C++ 中实现多态行为?

我是 C++ 的这些重要特性的新手,我已经在这里阅读了一些关于这些主题的问题/答案,并搜索了一些文档.但我仍然对此感到困惑......

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.

推荐答案

这是我听过的对多态性最好的解释:

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();

你抓住第一只动物,把它扔到墙上,你会听到喵!"- 是的,那是猫.然后你抓住下一个,扔掉它,你会听到MOOO!"- 那是牛.这就是多态性.

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.

您还应该检查 C++ 中的多态性

如果您正在寻找好书,这里有一份很好的清单:权威的 C++ 书籍指南和清单

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

相关文章