How to use virtual functions to achieve a polymorphic behavior in C++?(如何使用虚函数在 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
这篇关于如何使用虚函数在 C++ 中实现多态行为?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何使用虚函数在 C++ 中实现多态行为?
基础教程推荐
- 您如何将 CreateThread 用于属于类成员的函数? 2021-01-01
- 如何在 C++ 中处理或避免堆栈溢出 2022-01-01
- 设计字符串本地化的最佳方法 2022-01-01
- 什么是T&&(双与号)在 C++11 中是什么意思? 2022-11-04
- C++ 程序在执行 std::string 分配时总是崩溃 2022-01-01
- 调用std::Package_TASK::Get_Future()时可能出现争用情况 2022-12-17
- C++,'if' 表达式中的变量声明 2021-01-01
- 如何定义双括号/双迭代器运算符,类似于向量的向量? 2022-01-01
- 运算符重载的基本规则和习语是什么? 2022-10-31
- C++ 标准:取消引用 NULL 指针以获取引用? 2021-01-01