为什么我们需要 C++ 中的虚函数? [英] Why do we need virtual functions in C++?

查看:33
本文介绍了为什么我们需要 C++ 中的虚函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在学习 C++,我刚刚接触虚函数.

I'm learning C++ and I'm just getting into virtual functions.

根据我所读到的(在书中和在线),虚函数是基类中的函数,您可以在派生类中覆盖它们.

From what I've read (in the book and online), virtual functions are functions in the base class that you can override in derived classes.

但在本书前面,在学习基本继承时,我能够在不使用 virtual 的情况下覆盖派生类中的基函数.

But earlier in the book, when learning about basic inheritance, I was able to override base functions in derived classes without using virtual.

那么我在这里错过了什么?我知道虚函数还有更多,而且它似乎很重要,所以我想弄清楚它到底是什么.我只是在网上找不到直接的答案.

So what am I missing here? I know there is more to virtual functions, and it seems to be important so I want to be clear on what it is exactly. I just can't find a straightforward answer online.

推荐答案

这里是我理解的不只是什么 virtual 函数是,但为什么需要它们:

Here is how I understood not just what virtual functions are, but why they're required:

假设您有这两个类:

class Animal
{
    public:
        void eat() { std::cout << "I'm eating generic food."; }
};

class Cat : public Animal
{
    public:
        void eat() { std::cout << "I'm eating a rat."; }
};

在你的主函数中:

Animal *animal = new Animal;
Cat *cat = new Cat;

animal->eat(); // Outputs: "I'm eating generic food."
cat->eat();    // Outputs: "I'm eating a rat."

到目前为止一切顺利,对吧?动物吃普通食物,猫吃老鼠,都没有虚拟.

So far so good, right? Animals eat generic food, cats eat rats, all without virtual.

现在让我们稍微改变一下,以便通过中间函数调用 eat()(仅用于此示例的简单函数):

Let's change it a little now so that eat() is called via an intermediate function (a trivial function just for this example):

// This can go at the top of the main.cpp file
void func(Animal *xyz) { xyz->eat(); }

现在我们的主要功能是:

Now our main function is:

Animal *animal = new Animal;
Cat *cat = new Cat;

func(animal); // Outputs: "I'm eating generic food."
func(cat);    // Outputs: "I'm eating generic food."

呃哦...我们将一只猫传递给 func(),但它不会吃老鼠.你应该重载 func() 以便它需要一个 Cat* 吗?如果您必须从 Animal 中衍生出更多动物,它们都需要自己的 func().

Uh oh... we passed a Cat into func(), but it won't eat rats. Should you overload func() so it takes a Cat*? If you have to derive more animals from Animal they would all need their own func().

解决方案是使 Animal 类中的 eat() 成为一个虚函数:

The solution is to make eat() from the Animal class a virtual function:

class Animal
{
    public:
        virtual void eat() { std::cout << "I'm eating generic food."; }
};

class Cat : public Animal
{
    public:
        void eat() { std::cout << "I'm eating a rat."; }
};

主要内容:

func(animal); // Outputs: "I'm eating generic food."
func(cat);    // Outputs: "I'm eating a rat."

完成.

这篇关于为什么我们需要 C++ 中的虚函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆