多态的应用
不使用多态(不采用基类指针)
代码如下:
#include <iostream>
#include <cstring>
#include <algorithm>
using namespace std;
class Hero
{
public:
int damage;
string name;
Hero(int _damge, string _name): damage(_damge), name(_name) {}
virtual void skill1() = 0;
virtual void skill2() = 0;
virtual ~Hero() { cout << "调用了基类的析构函数" << endl;; }
};
class DC: public Hero
{
public:
DC(int _damage, string _name): Hero(_damage, _name) {}
void skill1()
{
cout << name << "释放了一技能" << endl;
}
void skill2()
{
cout << name << "释放了二技能" << endl;
}
virtual ~DC() { cout << "调用了派生类的析构函数" << endl;; }
};
class LB: public Hero
{
public:
LB(int _damage, string _name): Hero(_damage, _name) {}
void skill1()
{
cout << name << "释放了一技能" << endl;
}
void skill2()
{
cout << name << "释放了二技能" << endl;
}
virtual ~LB() { cout << "调用了派生类的析构函数" << endl;; }
};
class SWK: public Hero
{
public:
SWK(int _damage, string _name): Hero(_damage, _name) {}
void skill1()
{
cout << name << "释放了一技能" << endl;
}
void skill2()
{
cout << name << "释放了二技能" << endl;
}
virtual ~SWK() { cout << "调用了派生类的析构函数" << endl;; }
};
int main()
{
cout << "请选择英雄(貂蝉-1、李白-2、孙悟空-3):";
int id;
cin >> id;
if (id == 1)
{
DC h(6, "貂蝉");
h.skill1();
h.skill2();
}
else if (id == 2)
{
LB h(8, "李白");
h.skill1();
h.skill2();
}
else if (id == 3)
{
SWK h(9, "孙悟空");
h.skill1();
h.skill2();
}
return 0;
}
利用多态实现
代码如下:
#include <iostream>
#include <cstring>
#include <algorithm>
using namespace std;
class Hero
{
public:
int damage;
string name;
Hero(int _damge, string _name): damage(_damge), name(_name) {}
virtual void skill1() = 0;
virtual void skill2() = 0;
virtual ~Hero() { cout << "调用了基类的析构函数" << endl;; }
};
class DC: public Hero
{
public:
DC(int _damage, string _name): Hero(_damage, _name) {}
void skill1()
{
cout << name << "释放了一技能" << endl;
}
void skill2()
{
cout << name << "释放了二技能" << endl;
}
virtual ~DC() { cout << "调用了派生类的析构函数" << endl;; }
};
class LB: public Hero
{
public:
LB(int _damage, string _name): Hero(_damage, _name) {}
void skill1()
{
cout << name << "释放了一技能" << endl;
}
void skill2()
{
cout << name << "释放了二技能" << endl;
}
virtual ~LB() { cout << "调用了派生类的析构函数" << endl;; }
};
class SWK: public Hero
{
public:
SWK(int _damage, string _name): Hero(_damage, _name) {}
void skill1()
{
cout << name << "释放了一技能" << endl;
}
void skill2()
{
cout << name << "释放了二技能" << endl;
}
virtual ~SWK() { cout << "调用了派生类的析构函数" << endl;; }
};
int main()
{
cout << "请选择英雄(貂蝉-1、李白-2、孙悟空-3):";
int id;
cin >> id;
Hero* ptr = nullptr;
if (id == 1) ptr = new DC(6, "貂蝉");
else if (id == 2) ptr = new LB(8, "李白");
else if (id == 3) ptr = new SWK(9, "孙悟空");
ptr->skill1();
ptr->skill2();
delete ptr;
return 0;
}
总结
- 通过多态能够实现基类指针指向派生类对象
- 派生类通过重定义基类虚函数,能够自定义派生类的方法,使得基类指针能够调用派生类重定义的方法,从而实现简化开发,提升开发效率的目的