引入纯虚函数的目的:
在有些情况下,我们在父类中的某些函数,没有实现的必要,只想声明一下,然后让其子类对该函数进行重写,然后可以通过父类的指针或引用调用其子类重写的该虚函数,那么此时,我们就可以在父类的类体内,将该函数设置成纯虚函数。
代码:
#include <iostream>
using namespace std;
double cblood=2652;
class Hero
{
private:
string name;
double blood;
public:
Hero() {} //无参构造
Hero(string n,double b):name(n),blood(b){} //有参构造
virtual ~Hero(){} //纯虚析构函数
virtual double attackc(double b)=0; //纯虚函数 //攻击水晶函数
};
class Tank : public Hero
{
private:
double attack; //攻击量
public:
Tank() {} //无参构造
Tank(string n,double b,double a):Hero(n,b),attack(a) {} //有参构造
~Tank(){} //纯虚析构函数
double attackc(double b) //纯虚函数 //攻击水晶函数
{
cblood-=b+attack;
return b+attack;
}
};
class Thug : public Hero
{
private:
double punish; //惩戒量
public:
Thug() {} //无参构造
Thug(string n,double b,double p):Hero(n,b),punish(p) {} //有参构造
~Thug(){} //纯虚析构函数
double attackc(double b) //纯虚函数 //攻击水晶函数
{
cblood-=b+punish;
return b+punish;
}
};
double fun(Hero &other,double b)
{
return other.attackc(b);
}
int main()
{
cout<< "****欢迎来到王者荣耀,小王祝大家开局赢好运!*****"<<endl;
cout <<"水晶总血量 " <<cblood<<endl;
Tank t1("张飞",1400,432); //坦克张飞攻击水晶
cout <<"张飞对水晶伤害 "<<fun(t1,240)<<endl;
cout <<"水晶剩余血量 " <<cblood<<endl;
Thug t2("阿珂",1226,1620);
cout <<"阿珂对水晶伤害 "<<fun(t2,360)<<endl; //刺客阿珂攻击水晶
cout <<"水晶剩余血量 " <<cblood<<endl;
cout<<endl<<"****阿珂补了水晶最后一刀,victory*****"<<endl;
return 0;
}
实现结果