c++ - 为什么我们需要 C++ 中的虚函数?

标签 c++ polymorphism virtual-functions

我正在学习 C++,并且刚刚接触虚函数。

据我所读(在书中和网上),虚函数是基类中的函数,您可以在派生类中覆盖这些函数。

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

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

最佳答案

这是我的理解方式,而不仅仅是 virtual功能是,但为什么需要它们:

假设您有这两个类:

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."

到目前为止还不错吧?动物吃普通食物,猫吃老鼠,所有这些都没有 virtual

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

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

现在我们的主要功能是:

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()

解决方案是使 Animal 类中的 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++ - 为什么我们需要 C++ 中的虚函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57592496/

相关文章:

c++ - 比较中单引号和双引号的意义是什么?

c++ - 是否可以动态绑定(bind) operator>?

c++ - 在C++中,是否有可能在父类(super class)中有一个方法,当每个子类调用该方法时,该方法会向该子类返回一个shared_ptr?

c++ - 提高该算法的速度

c++ - OpenCV - 如何捕获rtsp视频流

c++ - 将 std::ostream 的子级传递给需要 std::ostream * 的库

c++ - 多态性 - 不确定使用模板的派生类 - 派生函数返回模板类型

java - 通过父类(super class)对象的 ArrayList 访问子类方法?

C++在子类中调用虚方法

c++ - 类定义和函数签名中的宏有什么用?