我正在学习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*
?如果您必须从“动物”中衍生出更多动物,则它们都需要自己的动物func()
。
解决方案是eat()
从Animal
类中创建一个虚函数:
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."
做完了
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句