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

查看:114
本文介绍了为什么我们需要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 a 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 straight answer online.

推荐答案

我是一个C ++新手自己,但这里是我的理解不仅仅是什么虚拟函数,而是为什么它们是必需的:

I'm a C++ newbie myself, but here is how I understood not just what virtual functions are, but why they're required:

让我们假设你有这两个类:

Let's say you have these two classes:

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.

现在让我们改变一点, code> 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."



噢噢...我们将一个Cat传递给了 func code>,但它不会吃老鼠。如果你重载 func()所以它需要一个猫*?如果你必须从动物得到更多的动物,他们都需要自己的 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().

eat()一个虚拟函数:

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天全站免登陆