为什么在C++中需要虚函数

我自己是一个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的一篇 问答





  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值