首页 > 其他 > 详细

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

时间:2014-09-19 19:26:56      阅读:303      评论:0      收藏:0      [点我收藏+]

程序代码:

#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");
}


执行结果:

bubuko.com,布布扣


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

原文:http://blog.csdn.net/u010105970/article/details/39401177

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!