我自己是一个C++新手,这里是我对什么事虚函数,以及为什么我们需要它的理解:
我们有这样两个类:
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."; }
}
在你的main函数中有:
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(); }
现在我们的main函数是:
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()中,但是它并不吃老鼠。难道你要重载func(),让它接收一个Cat*?如果你需要从Animal中派生多个动物,它们都需要自己的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."; }
}
Main:
func(animal); // outputs: "I'm eating generic food."
func(cat); // outputs: "I'm eating a rat."
本文翻译自stackoverflow的一篇 问答。
最后
以上就是独特故事最近收集整理的关于为什么在C++中需要虚函数的全部内容,更多相关为什么在C++中需要虚函数内容请搜索靠谱客的其他文章。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复