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

发布于 2025-01-04 15:47:08 字数 179 浏览 2 评论 0原文

我对 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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

仅一夜美梦 2025-01-11 15:47:08

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

这个世界上有很多动物。它们中的大多数会发出一些声音:

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; }
};

现在想象一下,您有一个装有动物的大袋子,但您看不到它们。你只需抓住其中一个并将其扔到墙上即可。然后你听它的声音 - 这会告诉你它是什么种类的动物:

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

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

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

你抓住第一只动物,把它扔到墙上,你会听到“喵!” - 是的,那是猫。然后你抓住下一个,把它扔出去,你会听到“哞!”的声音。 - 那是牛。这就是多态性。

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

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

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

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文