【C++】动态多态(运行时多态)
#include <iostream>
using namespace std;
#define xuhanshu
class Animal {
public:
// 虚函数,允许在派生类中重写,也允许不重写,基类默认行为
#ifdef xuhanshu
virtual void sound() const {
cout << "Animal makes a sound" << endl;
}
#elif defined(chunxuhanshu)
//纯虚函数:定义接口,必须重写实现
virtual void sound() const = 0;
#endif
};
class Dog : public Animal {
public:
void sound() const override {
cout << "Dog barks" << endl;
}
};
class Cat : public Animal {
public:
void sound() const override {
cout << "Cat meows" << endl;
}
};
void makeSound(const Animal& animal) {
animal.sound(); // 基于实际对象类型调用正确的函数
}
int main() {
Dog dog;
Cat cat;
makeSound(dog); // 输出: Dog barks
makeSound(cat); // 输出: Cat meows
return 0;
}
虚函数:基类默认有实现,可以不需要重写,也可以重写;
纯虚函数:基类没有实现,必须要重写。
Dog和Cat类均继承了Animal类,并对Sound函数进行了重写。
静态多态:函数重载或运算符重载
class Printer
{
public:
void print(int i)
{
cout << int i << endl;
}
void print(double i)
{
cout << double i << endl;
}
}
int main()
{
Printer P;
P.print(1);
P.print(1.111);
return 0;
}