c++虚函数

参考链接:https://stackoverflow.com/questions/2391679/why-do-we-need-virtual-functions-in-c?answertab=votes#tab-top

现在有两个类

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."; }
};

主函数

int 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."
}

目前看来一切都好:动物吃东西,猫吃老鼠。
现在增加一个函数:

// This can go at the top of the main.cpp file
void func(Animal *xyz) {
      xyz->eat(); }

主函数改成

int 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."

}
I'm eating generic food.
I'm eating generic food.

如果将基类中的eat函数变成虚函数,问题得到解决

#include 




class Animal
{
     
public:
    virtual void eat() {
      std::cout << "I'm eating generic food.\n"; } //or not firtual
};

class Cat : public Animal
{
     
public:
    virtual void eat() override  {
      std::cout << "I'm eating a rat.\n"; }
};

// This can go at the top of the main.cpp file
void func(Animal *xyz) {
      xyz->eat(); }

int 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."


    func(animal); // Outputs: "I'm eating generic food."
    func(cat);    // Outputs: "I'm eating generic food."

}
I'm eating generic food.
I'm eating a rat.
I'm eating generic food.
I'm eating a rat.

PS:
①C++11中提供了override,写在子类eat函数名之后,函数体之前,表示覆盖,其实主要目的是用来提醒。
②一旦基类eat函数生命成为virtual,那么子类的eat都将成为virtual,写不写都行,建议写上,代码看着方便。

你可能感兴趣的:(c++虚函数)