有以下类,完成特殊成员函数
class Person {
string name;
int *age;
}
class Stu:public Person
{
const double score;
}
#include <iostream>
#include <string>
using namespace std;
class Person {
string name;
int *age ;
public:
// 无参构造函数
Person() : name(""), age(nullptr) {}
// 有参构造函数
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) {
name = other.name;
int* newAge = new int(*other.age);
delete age;
age = newAge;
}
return *this;
}
};
class Stu: public Person {
private:
const double score;
public:
Stu(string name, int age, double score):Person(name, age), score(score) {}
~Stu(){}
Stu(const Person &other):Person(other),score(score){}
Stu &operator=(const Person &other)
{
if(this!=&other)
{
Person::operator=(other);
}
return *this;
}
};
int main() {
Person person1("Alice", 25);
Person person2 = person1; // 拷贝构造函数被调用
person1 = person2; // 拷贝赋值函数被调用
Stu stu1("Bob", 30, 85.5);
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 attck;
public:
Hero(){}
Hero(string name,int hp,int attck):name(name),hp(hp),attck(attck)
{cout << "H的有参构造" << endl;}
virtual void Atk()
{
monster-=0;
}
};
class Master:public Hero
{
int ap_atk=50;
public:
Master(){}
Master(string name,int hp,int attck,int ap_atk):Hero(name,hp,attck),ap_atk(ap_atk)
{cout << "Master的有参构造" << endl;}
void Atk()
{
monster-=(attck+ap_atk);
}
};
class Shooter:public Hero
{
int ac_atk=100;
public:
Shooter(){}
Shooter(string name,int hp,int attck):Hero(name,hp,attck)
{cout << "Shooter的有参构造" << endl;}
void Atk() //对父类虚函数的重写
{
monster-=(attck+ac_atk);
}
};
int main()
{
Master m1("妲己",3000,100,90);
Shooter s1("小鲁班",3500,120);
Hero *p1 = &m1,*p2 = &s1;
int i = 0;
while(monster>0)
{
p1->Atk();
i++;
if(monster>0)
{
p2->Atk();
i++;
}
// m1.Atk();
// s1.Atk();
}
cout << i << endl;
return 0;
}