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、思维导图