原文链接:https://blog.csdn.net/weixin_43293737/article/details/86484688/
转载说明:感谢原作者!如有侵权,请联系我删除,谢谢!
为什么要使用多态?为了解决同一段代码在不同的对象调用时有不同的效果,避免了代码的冗余
实现多态的三个条件:
- 要有继承
- 要有虚函数重写
- 用父类指针(父类引用)指向子类对象…
#include "iostream"
using namespace std;
class animal
{
public:
virtual int eat()
{
return 10;
}
};
class plant
{
public:
int eat()
{
return 25;
}
};
class mouse :public animal//多态第一步,要有继承
{
public:
virtual int eat()//多态第二步,要有函数重写(重写发生在2个类之间,两个类之间有继承关系,且出现同名的函数;虚函数重写将发生多态)
{
return 20;
}
};
class bird :public animal
{
public:
virtual int eat()
{
return 30;
}
};
void playLand(animal &animal,plant *plant)//多态的第三步,用父类指针(父类引用)指向子类对象....//即在函数的形参使用父类的对象替代子类对象,但是在调用重写了的虚函数时,仍然调用的是传递过来子类对象的函数
{
if (animal.eat() > plant->eat())
{
cout << "动物赢了" << endl;
}
else
{
cout << "植物赢了" << endl;
}
}
void main()
{
animal animal1;
mouse mouse1;
bird bird1;
plant flowers;
playLand(animal1, &flowers);
playLand(mouse1, &flowers);
playLand(bird1, &flowers);
}