C++Day5作业

2、特殊函数

#include <iostream>

using namespace std;
class Person
{public:
    string name;
    int *age;

    //无参构造
    Person():name("zhangsan"),age(new int(20)){cout<<"Person无参构造"<<endl;}
    //有参构造
    Person(string name,int age):name(name),age(new int(age)){cout<<"Person有参构造"<<endl;}
    //析构
    ~Person(){delete age;cout<<"Person析构"<<endl;}
    //拷贝构造
    Person(const Person &other):name(other.name),age(new int(*(other.age))){cout<<"Stu拷贝构造"<<endl;}
    //拷贝赋值
    Person &operator=(const Person &other)
    {
        if(this != &other)
        {
            this->name = other.name;
            *(this->age) = *(other.age);
        }
        cout<<"Person拷贝赋值"<<endl;
        return *this;
    }
};
class Stu:public Person
{
    const double score;
public:
    //无参构造
    Stu():Person(),score(95){cout<<"Stu无参构造"<<endl;}
    //有参构造
    Stu(double score):Person(),score(score){cout<<"Stu有参构造"<<endl;}
    //析构
    ~Stu(){cout<<"Stu析构"<<endl;}
    //拷贝构造
    Stu(const Stu &other):score(other.score){cout<<"Stu拷贝构造"<<endl;}
    //拷贝赋值
    Stu &operator=(const Stu &other)
    {
        if(this!=&other)
        {
            Person::operator=(other);
        }
        cout<<"Stu拷贝赋值"<<endl;
        return *this;
    }
};
int main()
{
    Person p1;
    Person p2("zhangsan",20);
    Person p3 = p2;
    p1 = p2;
    Stu s1;
    Stu s2(95);
    Stu s3 = s2;
    s1 = s2;

    return 0;
}

2、打怪

#include <iostream>

using namespace std;
int monster = 10000;

class Hero
{
protected:
    string name;
    int hp;
    int attck;
public:
    //无参构造
    Hero():name("张百忍"),hp(100),attck(1){}
    //有参构造
    Hero(string name,int hp,int attck):name(name),hp(hp),attck(attck){}
    //虚函数
    virtual void Atk(){monster-=0;}
};

class Ap:public Hero
{
    int ap_ack;
public:
    //有参构造
    Ap(int ap_ack):Hero(),ap_ack(ap_ack){}
    //虚函数重写
    void Atk(){monster-=ap_ack;}
};

class Ad:public Hero
{
    int ad_ack;
public:
    //有参构造
    Ad(int ad_ack):Hero(),ad_ack(ad_ack){}
    //虚函数重写
    void Atk(){monster-=ad_ack;}
};
int main()
{
    Hero usr;
    Ap ap(200);
    Ad ad(220);
    int Round=0;
    while(1)
    {
        //每回合AD和AP各A一下
        ad.Atk();
        ap.Atk();
        Round++;
        if(monster<=0){ break;}
    }

    cout<<"总回合数:"<<Round<<endl;

    return 0;
}

3、思维导图

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值