1.
2.
#include <iostream>using namespace std;
class Person
{string name;int *age;public:Person():name("zhangsan"),age(new int (18)){cout << "Person的无参函数" << endl;}Person(string name,int *age):name("zhangsan"),age(new int(18)){cout << "Person的有参函数" << endl;}void show();~Person(){cout << "准备释放空间:" << age <<endl;delete age;cout << "Person的析构函数" << endl;}Person(const Person &other):name (other.name),age(new int(*(other.age))){cout << "Person的拷贝构造" << endl;}Person &operator=(const Person &other){this->name = other.name;*(this->age) =*(other.age);{cout << "Stu的拷贝赋值" << endl;}return *this;}
};
class Stu:public Person
{const double score;public:Stu():Person(),score(20){cout << "Stu的无参函数" << endl;}
Stu(double score):Person(),score(score){cout << "Stu的有参函数" << endl;}
~Stu(){cout << "Stu的析构函数" << endl;}
Stu(const Stu &other):Person(other),score(score){cout << "Stu拷贝构造" << endl;}
Stu &operator=(const Stu &other)
{Person::operator=(other);{cout << "Stu的拷贝赋值" << endl;}
return *this;
}
void show();
};
void Stu::show()
{cout << "score:" <<score <<endl;
}
void Person::show()
{cout<<"name:" <<name<<endl;cout << "*age:" <<*age <<endl;
}
int main()
{Stu s1;Stu s2;s1=s2;s1.Person::show();s2.Person::show();s1.show();s2.show();return 0;
}
3.
#include <iostream>
using namespace std;extern int monster;int monster = 10000;
class hero {
protected:string name;int blood;int attack;
public:hero() {}hero(string name, int hp, int attack) {this->name = name;this->blood = hp;this->attack = attack;}virtual void Atk() =0;
};class mage : public hero {int ap_attack = 50;
public:mage() {}mage(string name, int hp, int attack, int ap_attack) : hero(name, hp, attack) {this->ap_attack = ap_attack;}void Atk() {monster -= (attack +ap_attack);cout<<"法师攻击后怪物的血量:"<<monster<<endl;}
};class shooter : public hero {int ac_attack = 100;
public:shooter() {}shooter(string name, int hp, int attack, int ac_attack) : hero(name, hp, attack) {this->ac_attack = ac_attack;}void Atk() {monster -= (attack + ac_attack);cout<<"射手攻击后怪物的血量:"<<monster<<endl;}
};int main() {mage m("Mage", 100, 20, 50);shooter s("Shooter", 80, 30, 100);while(monster > 0){m.Atk();s.Atk();}cout << "怪物已被杀死!" << endl;return 0;
}