摘自stackoverflow: https://stackoverflow.com/a/2392656/11128312
假设你有这两个类:
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."
emm, 我们把猫送进了func(), 但是它不会吃老鼠,那么我们怎么改变呢?
解决方案就是从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."; }
};
Main function:
func(animal); // Outputs: "I'm eating generic food."
func(cat); // Outputs: "I'm eating a rat."
总结:
使用虚函数,您可以实现运行时多态性