简体   繁体   English

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

[英]How to use virtual functions to achieve a polymorphic behavior in 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. 我不熟悉C ++的这些重要功能,我已经在这里阅读了有关这些主题的一些问题/答案,并在Google中搜索了一些文档。 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();

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!" 然后抓起下一个,扔掉,听到“ MOOO!” - That was cow. -那是牛。 That's polymorphism. 那是多态性。

You should also check Polymorphism in c++ 您还应该检查c ++中的多态性

And if you are looking for good book, here is good list of 'em: The Definitive C++ Book Guide and List 如果您正在寻找好的书籍,那么这里是'em的很好的清单: The Definitive C ++ Book Guide and List

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM