C++ - 20230703

一. 思维导图

C++ - 20230703_第1张图片

二.练习

全局变量,int monster = 10000;定义英雄类hero,受保护的属性string name,int hp,int attck;公有的无参构造,有参构造,虚成员函数 void Atk(){blood-=0;},法师类继承自英雄类,私有属性 int ap_atk=50;重写虚成员函数void Atk(){blood-=(attck+ap_atk);};射手类继承自英雄类,私有属性 int ac_atk = 100;重写虚成员函数void Atk(){blood-=(attck+ac_atk);}实例化类对象,判断怪物何时被杀死。

#include 

using namespace std;

int monster = 10000;

class Hero {
protected:
    string name = "";
    int hp = 0;
    int attack = 0;
public:
    Hero(){}
    Hero(string name, int hp, int attack):name(name), hp(hp), attack(attack){}
    virtual void atk(){

    }
};

class Mega: public Hero {
private:
    int ap_atk = 50;
public:
    Mega(){}
    Mega(string name, int hp, int attack):Hero(name, hp, attack){}
    void atk() {
        monster -= (attack+ap_atk);
    }
};

class Adc: public Hero {
private:
    int ac_atk = 100;
public:
    Adc(){}
    Adc(string name, int hp, int attack):Hero(name, hp, attack){}
    void atk() {
        monster -= (attack+ac_atk);
    }
};



int main()
{
    Mega mega("法师", 100, 0);
    Adc adc("射手", 100, 0);

    int attackCount = 0;
    while(monster > 0) {
        mega.atk();
        adc.atk();
        attackCount++;
    }
    cout << "攻击" << attackCount << "次后,杀死怪物" << endl;
    return 0;
}

结果展示:
C++ - 20230703_第2张图片

你可能感兴趣的:(c++)