有以下类,完成特殊成员函数
#include <iostream>
using namespace std;
class Person
{
string name;
int *age;
public:
//有参构造
Person(string name,int age):name(name),age(new int(age)){}
//析构函数
~Person()
{
delete age;
}
//拷贝构造
Person(const Person &other):name(other.name),age(new int(*(other.age))){}
//拷贝赋值
Person &operator=(const Person &other)
{
if(this!=&other)
{
this->name=other.name;
*(this->age)=*(other.age);
}
return *this;
}
};
class Stu:public Person
{
const double score;
public:
//无参构造
Stu():Person("路人甲",18),score(60.0){}
//有参构造
Stu(string name,int age,double score):Person(name,age),score(score){}
//析构函数
~Stu(){}
//拷贝构造
Stu(const Stu &other):Person(other),score(other.score){}
//拷贝赋值
Stu &operator=(const Stu &other)
{
if(this!=&other)
{
Person::operator=(other);
}
return *this;
}
};
int main()
{
cout << "Hello World!" << endl;
return 0;
}
2尝试写:定义一个全局变量int monster=10000;定义一个英雄类Hero,受保护的属性,string nameint hp,int attck,写一个无参构造、有参构造,类中有虛函数:void Atk()(monster-=0;};法师类,公有继承白英雄类,私有属性:int ap ack;写有参,重写父类中的虚函数,射手类,公有继承自英雄类,私有属性:int ad ack;写有参构造,重写父类中的虚函数,主函数内完成调用,判断怪物何时被杀死。
#include <iostream>
using namespace std;
int monster=10000;
class Hero
{
protected:
string name;
int hp;
int attack;
//无参构造
Hero():name("路人甲"),hp(100),attack(5){}
//有参构造
Hero(string name,int hp,int attack):name(name),hp(hp),attack(attack){}
virtual void Atk(){monster-=0;}
};
class Mage:public Hero
{
int ap_ack;
public:
Mage(string name,int hp,int attack,int ap_ack):Hero(name,hp,attack),ap_ack(ap_ack){}
void Atk()
{
int t=0;
while(monster>=0)
{
monster-=ap_ack;
t++;
}
cout << "经历了" << t << "秒的战斗,怪物被" << name << "消灭了" << endl;
monster=10000;
}
};
class Archer:public Hero
{
int ad_ack;
public:
Archer(string name,int hp,int attack,int ad_ack):Hero(name,hp,attack),ad_ack(ad_ack){}
void Atk()
{
int t=0;
while(monster>=0)
{
monster-=ad_ack;
t++;
}
cout << "经历了" << t << "秒的战斗,怪物被" << name << "消灭了" << endl;
monster=10000;
}
};
int main()
{
Mage m1("维肯",500,23,95);
m1.Atk();
Archer a1("安娜",250,33,125);
a1.Atk();
return 0;
}