爲什麼在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的一篇問答





發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章