c++day5

 class Person

{

        string name;

        int *age;

}

class Stu:public Person

{

        const double score;

#include <iostream>

using namespace std;
class Person
{
private:
    string name;
    int *age;
public:
    //无参构造
    Person() {}
    //有参构造
    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){
        if(this!=&other){
            name=other.name;
            age=new int(*(other.age));
        }
        return *this;
    }
    void show(){
        cout<<name<<endl;
        cout<<*age<<endl;
    }
};
class Stu:public Person
{
private:
    const double score;
public:
    //无参构造
    Stu():score(10.1){}
    //有参构造
    Stu(string name,int age,const double score):Person(name,age),score(score){}
    //拷贝构造
    Stu(const Stu &other):Person(other),score(other.score){}
    //拷贝赋值
    Stu &operator=(const Stu &other){
        if(this!=&other){
            Person::operator=(other);
        }
        return *this;
    }
    void show(){
        Person::show();
        cout<<score<<endl;
    }
};
int main()
{
    Stu s("zhangsan",18,50.01);
    s.show();
    Stu s1(s);
    s1.show();
    return 0;
}

 

  1. 尝试写:定义一个全局变量int monster = 10000;定义一个英雄类Hero,受保护的属性,string name,int hp,int attck,写一个无参构造、有参构造,类中有虚函数:void Atk(){monster-=0;};法师类,公有继承自英雄类,私有属性:int ap_ack;写有参,重写父类中的虚函数,射手类,公有继承自英雄类,私有属性:int ad_ack;写有参构造,重写父类中的虚函数,主函数内完成调用,判断怪物何时被杀死。
#include <iostream>

using namespace std;
int monster=10000;
class Hero
{
private:
    string name;
    int hp;
    int attck;
public:
    //无参构造
    Hero() {}
    //有参构造
    Hero(string name,int hp,int attck):name(name),hp(hp),attck(attck){}
    //虚函数
    virtual void Atk(){monster-=0;}

};
//法师类
class Master:public Hero
{
private:
    int ap_ack;
public:
    Master() {}
    //有参构造
    Master(string name,int hp,int attck,int ap_ack):Hero(name,hp,attck),ap_ack(ap_ack){}
    //虚函数
    void Atk(){monster-=ap_ack;}
};
//射手类
class Shooter:public Hero
{
private:
    int ad_ack;
public:
    Shooter() {}
    //有参构造
    Shooter(string name,int hp,int attck,int ad_ack):Hero(name,hp,attck),ad_ack(ad_ack){}
    //虚函数
    void Atk(){monster-=ad_ack;}
};
int main()
{
    Master m1("wang",100,100,200);
    Shooter s1("li",100,100,500);
    Hero *p;
    while(monster){
        p=&m1;
        p->Atk();
        p=&s1;
        p->Atk();
    }
    cout<<"monster killed"<<endl;
    return 0;
}

 

  • 3
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值