C++ 多态性

多态

多态性意味着 "多种形式",当我们有许多通过继承相互关联的类时,就会发生多态。

如前一章所述;继承 允许我们从另一个类继承属性和方法。多态性 使用这些方法来执行不同的任务。这允许我们以不同的方式执行单个操作。

例如,考虑一个名为 Animal 的超类,它有一个名为 animalSound() 的方法。动物的亚类可以是猪、猫、狗、鸟,它们也有自己的动物声音(猪叫、猫叫等):

实例
  1. // 基类
  2. class Animal {
  3. public:
  4. void animalSound() {
  5. cout << "The animal makes a sound \n" ;
  6. }
  7. };
  8. // 派生类
  9. class Pig : public Animal {
  10. public:
  11. void animalSound() {
  12. cout << "The pig says: wee wee \n" ;
  13. }
  14. };
  15. // 派生类
  16. class Dog : public Animal {
  17. public:
  18. void animalSound() {
  19. cout << "The dog says: bow wow \n" ;
  20. }
  21. };

请记住,在 继承 一章中,我们使用:符号从类继承。

现在我们可以创建 PigDog 对象,并重写 animalSound() 方法:

实例
  1. #include <iostream>
  2. #include <string>
  3. using namespace std;
  4. // Base class
  5. class Animal {
  6. public:
  7. void animalSound() {
  8. cout << "The animal makes a sound \n" ;
  9. }
  10. };
  11. // Derived class
  12. class Pig : public Animal {
  13. public:
  14. void animalSound() {
  15. cout << "The pig says: wee wee \n" ;
  16. }
  17. };
  18. // Derived class
  19. class Dog : public Animal {
  20. public:
  21. void animalSound() {
  22. cout << "The dog says: bow wow \n" ;
  23. }
  24. };
  25. int main() {
  26. Animal myAnimal;
  27. Pig myPig;
  28. Dog myDog;
  29. myAnimal.animalSound();
  30. myPig.animalSound();
  31. myDog.animalSound();
  32. return 0;
  33. }

为什么以及何时使用 "继承" 和 "多态"?

  • 它对代码的可重用性很有用:在创建新类时重用现有类的属性和方法。