我正在学习 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/