#include <iostream>
using namespace std;
class Person
{
public:string name;int *age;//Person():name(name),age(new int(100)){cout<<"无参构造"<<endl;}Person(string name,int age):name(name),age(new int(100)){cout <<"P的有参构造"<<endl;}// Person(const double score,string name,int age):name(name),age(new int(100)){}void show();~Person(){cout <<"准备释放空间"<<age<<endl;delete age;cout <<"p的析构函数"<<endl;}Person &operator=(const Person &other){*(this->age)=*(other.age);cout <<"Person的拷贝赋值函数"<<endl;return *this;}
};
class Stu:public Person
{const double score;
public:Stu():Person("zhangsan",18),score(90){cout <<"Stu的无参构造"<<endl;}Stu(const double score,string name,int age):Person(name,age),score(score){cout <<"Stu的有参构造"<<endl;}Stu(const Stu &other):Person(other),score(other.score){ cout <<"s的拷贝构造"<<endl;}Stu &operator=(const Stu &other){Person::operator=(other);cout << "S的拷贝赋值"<<endl;return *this;}void show();
};
void Person::show()
{cout<<"name="<<name<<"age="<<age<<endl;
}
void Stu::show()
{cout<<"score="<<score<<endl;
}
int main()
{Stu s1;s1.show();const double score=20;Stu s2(score,"zhangsan",18);s2.show();return 0;
}
尝试写:定义一个全局变量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
{
protected:string name;int hp;int attack;
public:Hero():name(name),hp(hp),attack(attack){cout<<"无参构造"<<endl;}Hero(string name,int hp,int attack):name(name),hp(hp),attack(attack){cout <<"有参构造"<<endl;}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){cout <<"有参构造"<<endl;}void Atk(){monster-=ap_ack;}};
class Adc:public Hero
{int ad_ack;
public:Adc(string name,int hp,int attack,int ad_ack):Hero(name,hp,attack),ad_ack(ad_ack){cout<<"有参构造"<<endl;}void Atk(){monster-=ad_ack;}
};
int main()
{Mage m1("zhangsan",100,200,3000);Adc a1("lisi",500,100,3000);Hero *p;int count=0;while(monster){p=&m1;p->Atk();p=&a1;p->Atk();count++;}cout<<count<<endl;cout<<"kill monster"<<endl;return 0;
}