多态的应用《植物大战僵尸》

程序代码:

#include <iostream>

using namespace std;

class SmallPlant//小型植物
{
public:
    //攻击力
     virtual int AttackPower()
    {
        return 10;//攻击力为10
    }
};

class Zombie//僵尸
{
public:
     //攻击力
    int DestoryPower()
    {
        return 15;//攻击力为15
    }
};

//植物大战僵尸
void Attack(SmallPlant *p, Zombie *z)
{
    if(p->AttackPower() > z->DestoryPower())
    {
        cout<<"植物战胜了僵尸!"<<endl;
    }
    else
    {
        cout<<"僵尸战胜了植物!"<<endl;
    }
}

//小型植物派生出大型植物
class BigPlant : public SmallPlant
{
public:
 //攻击力
     int AttackPower()
    {
        return 20;//攻击力为15
    }
};

void main()
{
    SmallPlant p;//小型植物
    Zombie z;//僵尸
    BigPlant p1;//大型植物

    //植物大战僵尸
    Attack (&p, &z);

    Attack(&p1, &z);

    system("pause");
}


运行结果:


原文地址:https://www.cnblogs.com/yfceshi/p/6857149.html