dynamic_cast使用
#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;
}
void show()
{
cout << "我是貂蝉!!!!!" << 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()
{
int id = 1;
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();
DC* dptr = dynamic_cast<DC*>(ptr);
if (dptr != nullptr) dptr->show();
delete ptr;
return 0;
}