2024.4.28

文章详细介绍了C++中的类结构,包括Person和Stu类的构造函数、析构函数以及多态的体现,如Hero类及其派生类Wizard和Archer的使用,展示了面向对象编程中继承、封装和虚函数的概念。
摘要由CSDN通过智能技术生成

#include <iostream>
using namespace std;
class Person
{
public:
    string name;
    int *age;
    
    Person():age(new int){}
    Person(string name,int *age):name(name),age(new int(*age)){}
    Person(const Person &other):name(other.name),age(new int(*(other.age))){}
    Person &operator=(const Person &other)
    {
        this->name = other.name;
        *(this->age) = *(other.age);
    }
    ~Person()
    {
        delete age;
    }
    
};

class Stu:public Person
{
public:
    const double score;
    
    //透传函数
    Stu():Person(),score(10){}
    Stu(const double score,string name,int *age):score(score),Person(name,age){}
    
    //继承构造
    using Person::Person;
//    Stu():Person(),score(20){}
//    Stu(string name,int *age):Person(name,age),score(10){}
    
    //委托构造
    Stu(const double score):Person(),score(score){}
    
    //拷贝构造
    Stu(const Stu &other):Person(other),score(other.score){}
    
    //拷贝赋值
    Stu &operator=(const Stu &other)
    {
        Person::operator=(other);
    }
    
    //析构函数
    ~Stu(){}
};

int main()
{
    cout << "Hello World!" << endl;
    return 0;
}

打怪兽

#include <iostream>
using namespace std;

int monster = 10000;
class Hero
{
protected:
    string name;
    int HP;
    int attack;
public:
    Hero(){}
    Hero(string name,int HP,int attack):name(name),HP(HP),attack(attack){}
    void virtual Atk()
    {
        monster -=attack;
    }
};

class Wizard:public Hero
{
    int ap_atk;
public:
    Wizard(string name,int HP,int attack):Hero(name,HP,attack),ap_atk(attack)
    {
        cout << "法师已加入" << endl;
        cout << "   昵称" << Wizard::name << endl;
        cout << "   血量" << Wizard::HP << endl;
        cout << "   法术伤害" << Wizard::ap_atk << endl;
    }
    void Atk()
    {
        monster -=ap_atk;
    }
};

class Archer:public Hero
{
    int ad_atk;
public:
    Archer(string name,int HP,int attack):Hero(name,HP,attack),ad_atk(attack)
    {
        cout << "射手已加入" << endl;
        cout << "   昵称" << Archer::name << endl;
        cout << "   血量" << Archer::HP << endl;
        cout << "   远程伤害" << Archer::ad_atk << endl;
    }
    void Atk()
    {
        monster -=ad_atk;
    }
};

int main()
{
    Wizard w1("BB",3000,200);
    Archer a1("WM",3500,250);
    putchar(10);
    int cout_w=0,cout_a=0;
    while(1)
    {
        if(monster<=0)
        {
            cout << "怪物已被击败" << endl;
            break;
        }

        w1.Atk();cout_w++;
        a1.Atk();cout_a++;
    }
    printf("法师攻击了 %d 次\n",cout_w);
    printf("射手攻击了 %d 次\n",cout_a);
    return 0;
}

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值