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/56907946/

相关文章:

c++ - 使用基类指针访问继承变量

c++ - 构造一个 unordered_map,值为一对字符串和对象类型

c++ - 对指向数组的数据结构进行排序 C++

c++ - 向下转换实际上有用吗?

C#:派生类上具有不同返回类型的属性

java - 为什么一个类能够转换一个只有运行时错误而不是编译器错误的不相关类

inheritance - 内联私有(private)和 protected 虚函数调用

c++ - C 风格类型转换困惑

c++ - Oracle OCI 将无效的 UTF8 字符更改为 U+FFFD

c++ - 使重写的虚函数成为非虚函数的目的