#include <iostream>
#include <string>
class Animal {
public:
virtual void makeSound() = 0; // 纯虚函数,所有的动物都应该提供自己的叫声
};
class Dog : public Animal {
public:
void makeSound() override {
std::cout << "Woof!" << std::endl;
}
};
class Cat : public Animal {
public:
void makeSound() override {
std::cout << "Meow!" << std::endl;
}
};
int main() {
Dog dog;
Cat cat;
dog.makeSound(); // 输出: Woof!
cat.makeSound(); // 输出: Meow!
return 0;
}
虚函数的存在使得在父类中声明的方法 makesound() 能够在子类中 makesound() 被重新定义(覆盖),从而在运行时确定调用哪个方法的实现
标签:makeSound,函数,class,c++,面对,void,Animal,include,public From: https://blog.csdn.net/weixin_74231706/article/details/139504639