背景

1.PNG
2.PNG
3.PNG

基本思路

4.PNG
5.PNG

非多态实现方法

6.PNG
7.PNG

非多态实现方法的缺点

8.PNG

改进方法

每增加一个新的类,则要增加2n个成员函数,即使已有的类中也是一大堆成员函数,然而这么多成员函数,唯一不一样的地方仅仅是作用的类不同,而这些类都派生自同一个基类。
根据公有派生的赋值兼容规则以及多态的基本概念,用多态实现可以大大减少初始代码量以及改动时所增加的代码量。

多态实现方法

  1. #include <bits/stdc++.h>
  2. using namespace std;
  3. class creature //基类各类成员函数就一个,其他所有派生类亦如此
  4. {
  5. protected:
  6. int HP;
  7. int power;
  8. public:
  9. creature(int x, int y) : HP(x), power(y) {}
  10. virtual void attack(creature &obj);
  11. virtual void hurt(int damage);
  12. virtual void fight_back(creature &obj);
  13. void print(void) { cout << "HP: " << HP << " "
  14. << "Power: " << power << endl; }
  15. };
  16. void creature::attack(creature &obj)
  17. {
  18. obj.hurt(this->power); //多态,obj所属类由传入的参数决定,理论上可以是所有派生类
  19. obj.fight_back(*this); //多态
  20. }
  21. void creature::hurt(int damage) { HP -= damage; } //多态
  22. void creature::fight_back(creature &obj) { obj.HP -= this->power / 2; } //多态
  23. //Dividing Line----------------------------------------------------------------------------------------------
  24. class dragon : public creature //继承所有基类的虚函数
  25. {
  26. public:
  27. dragon(int x, int y) : creature(x, y) {}
  28. };
  29. class ghost : public creature //继承所有基类的虚函数
  30. {
  31. public:
  32. ghost(int x, int y) : creature(x, y) {}
  33. };
  34. class soldier : public creature //继承所有基类的虚函数
  35. {
  36. public:
  37. soldier(int x, int y) : creature(x, y) {}
  38. };
  39. //Dividing Line---------------------------------------------------------------------------------------------
  40. int main(void)
  41. {
  42. dragon Dra(3000, 500);
  43. ghost Gho(1500, 300);
  44. soldier Sol(1000, 200);
  45. Dra.attack(Gho); //根据多态和虚函数的概念,这里调用Ghost::hurt()和Ghost::fight_back()
  46. Dra.attack(Sol); //根据多态和虚函数的概念,这里调用Soldier::hurt()和Soldier::fight_back()
  47. Dra.print();
  48. Gho.print();
  49. Sol.print();
  50. return 0;
  51. }
  52. /*
  53. HP: 2750 Power: 500
  54. HP: 1000 Power: 300
  55. HP: 500 Power: 200
  56. */

多态实现方法的优势

如果增加新的怪物(新的类),不需要在已有的类里新增加作用于新怪物的成员函数,已有的类可以原封不动,只需要编写新类即可,极大地减少工作量,提高效率。