C++ 多态

创建于 2024-12-03 / 25
字体: [默认] [大] [更大]

多态

多态性意味着许多形式,当我们有许多类通过继承相互关联时,多态性就会出现。

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

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

实例

// 基类
class Animal {
  public:
    void animalSound() {
    cout << "The animal makes a sound \n" ;
  }
};

// 派生类
class Pig : public Animal {
  public:
    void animalSound() {
    cout << "The pig says: wee wee \n" ;
  }
};

// 派生类
class Dog : public Animal {
  public:
    void animalSound() {
    cout << "The dog says: bow wow \n" ;
  }
};

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

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

实例

// 基类
class Animal {
  public:
    void animalSound() {
    cout << "The animal makes a sound \n" ;
  }
};

// 派生类
class Pig : public Animal {
  public:
    void animalSound() {
    cout << "The pig says: wee wee \n" ;
   }
};

// 派生类
class Dog : public Animal {
  public:
    void animalSound() {
    cout << "The dog says: bow wow \n" ;
  }
};

int main() {
  Animal myAnimal;
  Pig myPig;
  Dog myDog;

  myAnimal.animalSound();
  myPig.animalSound();
  myDog.animalSound();
  return 0;
} 运行实例 »

为什么要使用继承和多态?

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



0 人点赞过