码迷,mamicode.com
首页 > 其他好文 > 详细

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

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

标签:des   style   blog   http   io   os   2014   sp   代码   

程序代码:

#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,布布扣


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

标签:des   style   blog   http   io   os   2014   sp   代码   

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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!