虚函数基本概念

class Animal {
public:
    virtual void makeSound() {
        std::cout << "The animal makes a sound." << std::endl;
    }
};
class Dog : public Animal {
public:
    void makeSound() override {
        std::cout << "The dog barks." << std::endl;
    }
};
class Cat : public Animal {
public:
    void makeSound() override {
        std::cout << "The cat meows." << std::endl;
    }
};
Animal* animal = new Dog();
animal->makeSound();  // Output: "The dog barks."

animal = new Cat();
animal->makeSound();  // Output: "The cat meows."
  • 上面两块代码中Animal 的makeSound()是作为虚函数存在。虚函数允许子类(派生类)对其进行重写(override),从而实现多态性。。在 Animal 类中,makeSound() 函数的默认行为是输出一条消息 "The animal makes a sound."。子类可以对 makeSound() 进行重写,以实现特定的行为。
posted @ 2023-03-21 15:40  Lachlan_Yang  阅读(15)  评论(0编辑  收藏  举报