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;
}
- 尝试写:定义一个全局变量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;
}